diff --git a/CMakeLists.txt b/CMakeLists.txt index 7de42d0ebe..0dccd4b7af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -849,9 +849,11 @@ if (INSTALL_SAMPLES) OCCT_INSTALL_FILE_OR_DIR ("samples/java" "${INSTALL_DIR_SAMPLES}") OCCT_INSTALL_FILE_OR_DIR ("samples/ocafsamples" "${INSTALL_DIR_SAMPLES}") OCCT_INSTALL_FILE_OR_DIR ("samples/qt" "${INSTALL_DIR_SAMPLES}") + OCCT_INSTALL_FILE_OR_DIR ("samples/OCCTOverview/code" "${INSTALL_DIR_SAMPLES}/OCCTOverview") install (FILES "${CMAKE_BINARY_DIR}/env.samples.${SCRIPT_EXT}" DESTINATION "${INSTALL_DIR_SAMPLES}/qt/FuncDemo" RENAME "env.${SCRIPT_EXT}") install (FILES "${CMAKE_BINARY_DIR}/env.samples.${SCRIPT_EXT}" DESTINATION "${INSTALL_DIR_SAMPLES}/qt/IESample" RENAME "env.${SCRIPT_EXT}") + install (FILES "${CMAKE_BINARY_DIR}/env.samples.${SCRIPT_EXT}" DESTINATION "${INSTALL_DIR_SAMPLES}/qt/OCCTOverview" RENAME "env.${SCRIPT_EXT}") install (FILES "${CMAKE_BINARY_DIR}/env.samples.${SCRIPT_EXT}" DESTINATION "${INSTALL_DIR_SAMPLES}/qt/Tutorial" RENAME "env.${SCRIPT_EXT}") endif() diff --git a/adm/SAMPLES b/adm/SAMPLES index d993165b31..92496b7397 100644 --- a/adm/SAMPLES +++ b/adm/SAMPLES @@ -1 +1 @@ -qt AndroidQt FuncDemo IESample Tutorial \ No newline at end of file +qt AndroidQt FuncDemo IESample Tutorial OCCTOverview \ No newline at end of file diff --git a/adm/SAMPLES_RESOURCES b/adm/SAMPLES_RESOURCES index a353f3f6e6..42b0dea440 100644 --- a/adm/SAMPLES_RESOURCES +++ b/adm/SAMPLES_RESOURCES @@ -1,2 +1,3 @@ qt/Common/res/ -qt/Tutorial/res/ \ No newline at end of file +qt/Tutorial/res/ +qt/OCCTOverview/res/ \ No newline at end of file diff --git a/adm/templates/env.bat.in b/adm/templates/env.bat.in index d695c22500..624ea48d05 100644 --- a/adm/templates/env.bat.in +++ b/adm/templates/env.bat.in @@ -140,7 +140,10 @@ if not ["%GLES2_DIR%"] == [""] set "PATH=%GLES2_DIR%;%PATH%" if not ["%TBB_DIR%"] == [""] set "PATH=%TBB_DIR%;%PATH%" if not ["%VTK_DIR%"] == [""] set "PATH=%VTK_DIR%;%PATH%" if not ["%FFMPEG_DIR%"] == [""] set "PATH=%FFMPEG_DIR%;%PATH%" -if not ["%QTDIR%"] == [""] set "PATH=%QTDIR%/bin;%PATH%" +if not ["%QTDIR%"] == [""] ( + set "PATH=%QTDIR%/bin;%PATH%" + set "QT_PLUGIN_PATH=%QTDIR%/plugins" +) rem ----- Set path to 3rd party and OCCT libraries ----- if not "%CSF_OCCTBinPath%" == "" ( diff --git a/adm/templates/env.samples.bat.in b/adm/templates/env.samples.bat.in index e855e61336..7cbb822ff1 100644 --- a/adm/templates/env.samples.bat.in +++ b/adm/templates/env.samples.bat.in @@ -27,3 +27,5 @@ if not "%QTDIR%" == "" ( set "PATH=%QTDIR%/bin;%PATH%" set "QT_QPA_PLATFORM_PLUGIN_PATH=%QTDIR%\plugins\platforms" ) + +set "CSF_OCCTOverviewSampleCodePath=%~dp0..\..\OCCTOverview\code" diff --git a/adm/templates/env.samples.sh.in b/adm/templates/env.samples.sh.in index d497aad35d..dddd137f21 100644 --- a/adm/templates/env.samples.sh.in +++ b/adm/templates/env.samples.sh.in @@ -20,3 +20,5 @@ export STATION=$host export RES_DIR=${aSamplePath}/${STATION}/res export PATH=${QTDIR}/bin:${PATH} + +export "CSF_OCCTOverviewSampleCodePath=${aSamplePath}/../../OCCTOverview/code" diff --git a/adm/templates/sample.bat b/adm/templates/sample.bat index e7446dda3f..63b79cc876 100644 --- a/adm/templates/sample.bat +++ b/adm/templates/sample.bat @@ -19,6 +19,7 @@ if ["%1"] == [""] ( echo AndroidQt echo FuncDemo echo IESample + echo OCCTOverview echo Tutorial PAUSE exit /B @@ -35,5 +36,8 @@ if not exist "%EXE_PATH%" ( exit /B ) +rem Set path to location where sample code is installed +set "CSF_OCCTOverviewSampleCodePath=%~dp0samples\OCCTOverview\code" + "%EXE_PATH%" diff --git a/adm/templates/sample.sh b/adm/templates/sample.sh index 44e337a0f9..1d6b75055b 100644 --- a/adm/templates/sample.sh +++ b/adm/templates/sample.sh @@ -8,6 +8,7 @@ if [ "$1" == "" ]; then echo available samples: echo FuncDemo echo IESample + echo OCCTOverview echo Tutorial fi @@ -31,5 +32,7 @@ if [ ! -f "$EXE_PATH" ]; then exit 1 fi +export CSF_OCCTOverviewSampleCodePath="${aCurrentPath}/samples/qt/OCCTOverview/code" + cd ${aCurrentPath} "$EXE_PATH" \ No newline at end of file diff --git a/dox/FILES_HTML.txt b/dox/FILES_HTML.txt index 5fbca28ed3..b71332f5a7 100644 --- a/dox/FILES_HTML.txt +++ b/dox/FILES_HTML.txt @@ -12,6 +12,7 @@ samples/samples.md ../samples/CSharp/ReadMe.md ../samples/CSharp/ReadMe_D3D.md ../samples/qt/AndroidQt/ReadMe.md +../samples/qt/OCCTOverview/ReadMe.md ../samples/java/jniviewer/ReadMe.md ../samples/ios/UIKitSample/ReadMe.md ../samples/webgl/ReadMe.md diff --git a/dox/introduction/images/overview_c__ie.png b/dox/introduction/images/overview_c__ie.png deleted file mode 100644 index 3cfc12e82c..0000000000 Binary files a/dox/introduction/images/overview_c__ie.png and /dev/null differ diff --git a/dox/introduction/images/overview_mvc.png b/dox/introduction/images/overview_mvc.png deleted file mode 100644 index f4104834e6..0000000000 Binary files a/dox/introduction/images/overview_mvc.png and /dev/null differ diff --git a/dox/introduction/images/overview_qt.png b/dox/introduction/images/overview_qt.png deleted file mode 100644 index e4c688585c..0000000000 Binary files a/dox/introduction/images/overview_qt.png and /dev/null differ diff --git a/dox/introduction/images/sample_ios_uikit.png b/dox/introduction/images/sample_ios_uikit.png deleted file mode 100644 index 703e8e5e4f..0000000000 Binary files a/dox/introduction/images/sample_ios_uikit.png and /dev/null differ diff --git a/dox/introduction/images/sample_webgl.png b/dox/introduction/images/sample_webgl.png deleted file mode 100644 index 7d3781faad..0000000000 Binary files a/dox/introduction/images/sample_webgl.png and /dev/null differ diff --git a/dox/introduction/images/samples_java_android_occt.jpg b/dox/introduction/images/samples_java_android_occt.jpg deleted file mode 100644 index ecba47332b..0000000000 Binary files a/dox/introduction/images/samples_java_android_occt.jpg and /dev/null differ diff --git a/dox/introduction/images/samples_qml_android_occt.jpg b/dox/introduction/images/samples_qml_android_occt.jpg deleted file mode 100644 index 3fbdbd34a3..0000000000 Binary files a/dox/introduction/images/samples_qml_android_occt.jpg and /dev/null differ diff --git a/dox/samples/images/overview_overview_qt.png b/dox/samples/images/overview_overview_qt.png deleted file mode 100644 index 9ec815c13f..0000000000 Binary files a/dox/samples/images/overview_overview_qt.png and /dev/null differ diff --git a/dox/samples/images/sample_overview_qt.png b/dox/samples/images/sample_overview_qt.png new file mode 100644 index 0000000000..76850440a9 Binary files /dev/null and b/dox/samples/images/sample_overview_qt.png differ diff --git a/dox/samples/samples.md b/dox/samples/samples.md index 01e06ef975..943db58e57 100644 --- a/dox/samples/samples.md +++ b/dox/samples/samples.md @@ -46,7 +46,10 @@ See @subpage samples_mfc_standard "Readme" for details. Qt --- - OCCT contains three samples based on Qt application framework + OCCT includes several samples based on Qt application framework. +These samples are available on all supported desktop platforms. + +To start a sample on Windows use Open CASCADE Technology\\Samples\\Qt\\ item of the Start\\Programs menu. Import Export ------------- @@ -69,6 +72,27 @@ The combination of these resources allows creating substantial applications. **See also:** @ref occt__tutorial "OCCT Tutorial" +Overview +--------- + +The Qt application providing samples for basic usage of C++ API of various OCCT functionality. + +The samples are organized in several categories according to relevant module of OCCT: + + * Geometry + * Topology, + * Triangulation + * DataExchange + * OCAF + * Viewer 2d + * Viewer 3d + +Each sample presents geometry view, C++ code fragment and sample output window. + +@figure{/samples/images/sample_overview_qt.png} + +See \subpage samples_qt_overview "Readme" for details. + C# --- diff --git a/samples/OCCTOverview/code/AdaptorCurve2d_AIS.cxx b/samples/OCCTOverview/code/AdaptorCurve2d_AIS.cxx new file mode 100644 index 0000000000..b17d89cb09 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorCurve2d_AIS.cxx @@ -0,0 +1,147 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "AdaptorCurve2d_AIS.h" + +#include <Prs3d_LineAspect.hxx> +#include <Prs3d_PointAspect.hxx> +#include <StdPrs_PoleCurve.hxx> +#include <Geom2dAdaptor_Curve.hxx> +#include <GCPnts_QuasiUniformDeflection.hxx> +#include <Graphic3d_ArrayOfPolylines.hxx> +#include <Geom2d_BezierCurve.hxx> +#include <Geom2d_BSplineCurve.hxx> +#include <Geom2dLProp_CLProps2d.hxx> + +AdaptorCurve2d_AIS::AdaptorCurve2d_AIS (const Handle(Geom2d_Curve)& theGeom2dCurve, + const Aspect_TypeOfLine theTypeOfLine, + const Aspect_WidthOfLine theWidthOfLine) +: myGeom2dCurve (theGeom2dCurve), + myTypeOfLine (theTypeOfLine), + myWidthOfLine (theWidthOfLine), + myDisplayPole (Standard_True), + myDisplayCurbure (Standard_False), + myDiscretisation (20), + myradiusmax (10), + myradiusratio (1) +{ + // +} + +void AdaptorCurve2d_AIS::Compute (const Handle(PrsMgr_PresentationManager3d)&, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) +{ + if (theMode != 0) + { + return; + } + + Geom2dAdaptor_Curve anAdaptor(myGeom2dCurve); + GCPnts_QuasiUniformDeflection anEdgeDistrib(anAdaptor, 1.e-2); + if (anEdgeDistrib.IsDone()) + { + Handle(Graphic3d_ArrayOfPolylines) aCurve = new Graphic3d_ArrayOfPolylines(anEdgeDistrib.NbPoints()); + for (Standard_Integer i = 1; i <= anEdgeDistrib.NbPoints(); ++i) + { + aCurve->AddVertex(anEdgeDistrib.Value(i)); + } + + Handle(Graphic3d_Group) aPrsGroup = thePrs->NewGroup(); + aPrsGroup->SetGroupPrimitivesAspect(myDrawer->LineAspect()->Aspect()); + aPrsGroup->AddPrimitiveArray(aCurve); + } + + if (myDisplayPole) + { + if (anAdaptor.GetType() == GeomAbs_BezierCurve) + { + Handle(Geom2d_BezierCurve) aBezier = anAdaptor.Bezier(); + Handle(Graphic3d_ArrayOfPolylines) anArrayOfVertex = new Graphic3d_ArrayOfPolylines(aBezier->NbPoles()); + for (int i = 1; i <= aBezier->NbPoles(); i++) + { + gp_Pnt2d CurrentPoint = aBezier->Pole(i); + anArrayOfVertex->AddVertex(CurrentPoint.X(), CurrentPoint.Y(), 0.); + } + + Handle(Graphic3d_Group) aPrsGroup = thePrs->NewGroup(); + aPrsGroup->SetGroupPrimitivesAspect(myDrawer->LineAspect()->Aspect()); + aPrsGroup->AddPrimitiveArray(anArrayOfVertex); + } + + if (anAdaptor.GetType() == GeomAbs_BSplineCurve) + { + Handle(Geom2d_BSplineCurve) aBSpline = anAdaptor.BSpline(); + Handle(Graphic3d_ArrayOfPolylines) anArrayOfVertex = new Graphic3d_ArrayOfPolylines(aBSpline->NbPoles()); + for (int i = 1; i <= aBSpline->NbPoles(); i++) + { + gp_Pnt2d CurrentPoint = aBSpline->Pole(i); + anArrayOfVertex->AddVertex(CurrentPoint.X(), CurrentPoint.Y(), 0.); + } + + Handle(Graphic3d_Group) aPrsGroup = thePrs->NewGroup(); + aPrsGroup->SetGroupPrimitivesAspect(myDrawer->LineAspect()->Aspect()); + aPrsGroup->AddPrimitiveArray(anArrayOfVertex); + } + } + + if (myDisplayCurbure && (anAdaptor.GetType() != GeomAbs_Line)) + { + const Standard_Integer nbintv = anAdaptor.NbIntervals(GeomAbs_CN); + TColStd_Array1OfReal TI(1, nbintv + 1); + anAdaptor.Intervals(TI, GeomAbs_CN); + Standard_Real Resolution = 1.0e-9, Curvature; + Geom2dLProp_CLProps2d LProp(myGeom2dCurve, 2, Resolution); + gp_Pnt2d P1, P2; + + Handle(Graphic3d_Group) aPrsGroup = thePrs->NewGroup(); + aPrsGroup->SetGroupPrimitivesAspect (myDrawer->LineAspect()->Aspect()); + for (Standard_Integer intrv = 1; intrv <= nbintv; intrv++) + { + Standard_Real t = TI(intrv); + Standard_Real step = (TI(intrv + 1) - t) / GetDiscretisation(); + Standard_Real LRad, ratio; + for (Standard_Integer ii = 1; ii <= myDiscretisation; ii++) + { + LProp.SetParameter(t); + if (LProp.IsTangentDefined()) + { + Curvature = Abs(LProp.Curvature()); + if (Curvature > Resolution) + { + myGeom2dCurve->D0(t, P1); + LRad = 1. / Curvature; + ratio = ((LRad > myradiusmax) ? myradiusmax / LRad : 1); + ratio *= myradiusratio; + LProp.CentreOfCurvature(P2); + gp_Vec2d V(P1, P2); + gp_Pnt2d P3 = P1.Translated(ratio*V); + Handle(Graphic3d_ArrayOfPolylines) aSegment = new Graphic3d_ArrayOfPolylines(2); + aSegment->AddVertex(P1.X(), P1.Y(), 0.); + aSegment->AddVertex(P3.X(), P3.Y(), 0.); + aPrsGroup->AddPrimitiveArray(aSegment); + } + } + t += step; + } + } + } +} diff --git a/samples/OCCTOverview/code/AdaptorCurve2d_AIS.h b/samples/OCCTOverview/code/AdaptorCurve2d_AIS.h new file mode 100644 index 0000000000..abb5723d55 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorCurve2d_AIS.h @@ -0,0 +1,77 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef ADAPTOR_CURVE2D_AIS_H +#define ADAPTOR_CURVE2D_AIS_H + +#include <AIS_InteractiveObject.hxx> +#include <Geom2d_Curve.hxx> +#include <Aspect_TypeOfLine.hxx> +#include <Aspect_WidthOfLine.hxx> + +//! AIS interactive Object for Geom2d_Curve +class AdaptorCurve2d_AIS : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(AdaptorCurve2d_AIS, AIS_InteractiveObject) +public: + AdaptorCurve2d_AIS(const Handle(Geom2d_Curve)& theGeom2dCurve, + const Aspect_TypeOfLine theTypeOfline = Aspect_TOL_SOLID, + const Aspect_WidthOfLine theWidthOfLine = Aspect_WOL_MEDIUM); + + Standard_Integer NbPossibleSelection() const { return 1; } + Aspect_TypeOfLine GetTypeOfLine() const { return myTypeOfLine; } + void SetTypeOfLine(const Aspect_TypeOfLine aNewTypeOfLine) { myTypeOfLine = aNewTypeOfLine; } + Aspect_WidthOfLine GetWidthOfLine() const { return myWidthOfLine; } + void SetWidthOfLine(const Aspect_WidthOfLine aNewWidthOfLine) { myWidthOfLine = aNewWidthOfLine; } + Standard_Boolean GetDisplayPole() const { return myDisplayPole; } + void SetDisplayPole(const Standard_Boolean aNewDisplayPole) { myDisplayPole = aNewDisplayPole; } + Standard_Boolean GetDisplayCurbure() const { return myDisplayCurbure; } + void SetDisplayCurbure(const Standard_Boolean aNewDisplayCurbure) { myDisplayCurbure = aNewDisplayCurbure; } + Standard_Real GetDiscretisation() const { return myDiscretisation; } + void SetDiscretisation(const Standard_Real aNewDiscretisation) { myDiscretisation = aNewDiscretisation; } + +private: + //! Return TRUE for supported display modes (only 0 mode is supported). + virtual Standard_Boolean AcceptDisplayMode(const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; } + + //! Compute presentation. + virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection (not implemented). + virtual void ComputeSelection (const Handle(SelectMgr_Selection)&, + const Standard_Integer) Standard_OVERRIDE {} + +private: + + Handle(Geom2d_Curve) myGeom2dCurve; + Aspect_TypeOfLine myTypeOfLine; + Aspect_WidthOfLine myWidthOfLine; + Standard_Boolean myDisplayPole; + Standard_Boolean myDisplayCurbure; + Standard_Real myDiscretisation; + Standard_Real myradiusmax; + Standard_Real myradiusratio; + +}; + +#endif diff --git a/samples/OCCTOverview/code/AdaptorCurve_AIS.cxx b/samples/OCCTOverview/code/AdaptorCurve_AIS.cxx new file mode 100644 index 0000000000..21a692fc5b --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorCurve_AIS.cxx @@ -0,0 +1,49 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "AdaptorCurve_AIS.h" + +#include <GeomAdaptor_Curve.hxx> +#include <Prs3d_LineAspect.hxx> +#include <StdPrs_PoleCurve.hxx> +#include <StdPrs_Curve.hxx> + +void AdaptorCurve_AIS::Compute (const Handle(PrsMgr_PresentationManager3d)&, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) +{ + GeomAdaptor_Curve anAdaptorCurve(myCurve); + switch (theMode) + { + case 1: + { + Handle(Prs3d_Drawer) aPoleDrawer = new Prs3d_Drawer(); + aPoleDrawer->SetLineAspect(new Prs3d_LineAspect(Quantity_NOC_RED, Aspect_TOL_SOLID, 1.0)); + StdPrs_PoleCurve::Add(thePrs, anAdaptorCurve, aPoleDrawer); + } + Standard_FALLTHROUGH + case 0: + { + StdPrs_Curve::Add(thePrs, anAdaptorCurve, myDrawer); + break; + } + } +} diff --git a/samples/OCCTOverview/code/AdaptorCurve_AIS.h b/samples/OCCTOverview/code/AdaptorCurve_AIS.h new file mode 100644 index 0000000000..a01c99d7c7 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorCurve_AIS.h @@ -0,0 +1,52 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef ADAPTOR_CURVE_AIS_H +#define ADAPTOR_CURVE_AIS_H + +#include <AIS_InteractiveObject.hxx> +#include <Geom_Curve.hxx> + +//! AIS interactive Object for Geom_Curve +class AdaptorCurve_AIS : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(AdaptorCurve_AIS, AIS_InteractiveObject) +public: + AdaptorCurve_AIS (const Handle(Geom_Curve)& theCurve) : myCurve(theCurve) {} +private: + + //! Return TRUE for supported display modes (modes 0 and 1 are supported). + virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0 || theMode == 1; } + + //! Compute presentation. + Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection (not implemented). + virtual void ComputeSelection (const Handle(SelectMgr_Selection)&, + const Standard_Integer) Standard_OVERRIDE {} + +private: + Handle(Geom_Curve) myCurve; +}; + +#endif diff --git a/samples/OCCTOverview/code/AdaptorPnt2d_AIS.cxx b/samples/OCCTOverview/code/AdaptorPnt2d_AIS.cxx new file mode 100644 index 0000000000..80fdbf11d5 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorPnt2d_AIS.cxx @@ -0,0 +1,38 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "AdaptorPnt2d_AIS.h" + +#include <Geom_CartesianPoint.hxx> +#include <StdPrs_Point.hxx> + +void AdaptorPnt2d_AIS::Compute (const Handle(PrsMgr_PresentationManager3d)& , + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) +{ + if (theMode != 0) + { + return; + } + + Handle(Geom_CartesianPoint) aGeomPoint = new Geom_CartesianPoint(myPoint); + StdPrs_Point::Add (thePrs, aGeomPoint, myDrawer); +} diff --git a/samples/OCCTOverview/code/AdaptorPnt2d_AIS.h b/samples/OCCTOverview/code/AdaptorPnt2d_AIS.h new file mode 100644 index 0000000000..b34bee2b79 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorPnt2d_AIS.h @@ -0,0 +1,57 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef ADAPTOR_PNT2D_AIS_H +#define ADAPTOR_PNT2D_AIS_H + +#include <Geom2d_Point.hxx> +#include <AIS_InteractiveObject.hxx> + +//! AIS interactive Object for Geom2d_Point +class AdaptorPnt2d_AIS : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(AdaptorPnt2d_AIS, AIS_InteractiveObject) +public: + AdaptorPnt2d_AIS (const Handle(Geom2d_Point)& thePoint, + Standard_Real theElevation = 0) + : myPoint(thePoint->X(), thePoint->Y(), theElevation) {} + +private: + + //! Return TRUE for supported display modes (only mode 0 is supported). + virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; } + + //! Compute presentation. + virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection (not implemented). + virtual void ComputeSelection (const Handle(SelectMgr_Selection)&, + const Standard_Integer) Standard_OVERRIDE {} + +private: + + gp_Pnt myPoint; + +}; + +#endif // ADAPTOR_PNT2D_AIS_H diff --git a/samples/OCCTOverview/code/AdaptorVec_AIS.cxx b/samples/OCCTOverview/code/AdaptorVec_AIS.cxx new file mode 100644 index 0000000000..e344acda84 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorVec_AIS.cxx @@ -0,0 +1,77 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "AdaptorVec_AIS.h" + +#include <Graphic3d_ArrayOfSegments.hxx> +#include <Prs3d_ArrowAspect.hxx> +#include <Prs3d_LineAspect.hxx> +#include <Prs3d_Arrow.hxx> +#include <Prs3d_Text.hxx> + +AdaptorVec_AIS::AdaptorVec_AIS (const gp_Pnt2d& thePnt1, + const gp_Pnt2d& thePnt2, + Standard_Real theArrowLength) +: myPnt (gp_Pnt (thePnt1.X(), thePnt1.Y(), 0.0)), + myLength (0.0), + myArrowLength (theArrowLength) +{ + gp_Vec aVec (thePnt2.X() - thePnt1.X(), thePnt2.Y() - thePnt1.Y(), 0.0); + myDir = gp_Dir(aVec); + myLength = aVec.Magnitude(); +} + +void AdaptorVec_AIS::Compute (const Handle(PrsMgr_PresentationManager3d)& , + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) +{ + if (theMode != 0) + { + return; + } + + // Set style for arrow + Handle(Prs3d_ArrowAspect) anArrowAspect = myDrawer->ArrowAspect(); + anArrowAspect->SetLength(myArrowLength); + + gp_Pnt aLastPoint = myPnt; + aLastPoint.Translate(myLength*gp_Vec(myDir)); + + // Draw Line + { + Handle(Graphic3d_Group) aLineGroup = thePrs->NewGroup(); + aLineGroup->SetGroupPrimitivesAspect (myDrawer->LineAspect()->Aspect()); + Handle(Graphic3d_ArrayOfSegments) aPrims = new Graphic3d_ArrayOfSegments(2); + aPrims->AddVertex(myPnt); + aPrims->AddVertex(aLastPoint); + aLineGroup->AddPrimitiveArray(aPrims); + + // Draw arrow + Prs3d_Arrow::Draw (aLineGroup, aLastPoint, myDir, anArrowAspect->Angle(), anArrowAspect->Length()); + } + + // Draw text + if (!myText.IsEmpty()) + { + gp_Pnt aTextPosition = aLastPoint; + Prs3d_Text::Draw (thePrs->NewGroup(), myDrawer->TextAspect(), myText, aTextPosition); + } +} diff --git a/samples/OCCTOverview/code/AdaptorVec_AIS.h b/samples/OCCTOverview/code/AdaptorVec_AIS.h new file mode 100644 index 0000000000..25e02d7c86 --- /dev/null +++ b/samples/OCCTOverview/code/AdaptorVec_AIS.h @@ -0,0 +1,121 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef ADAPTOR_VEC_AIS_H +#define ADAPTOR_VEC_AIS_H + +#include <AIS_InteractiveObject.hxx> + +//! AIS interactive Object for vector with arrow and text +class AdaptorVec_AIS : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(AdaptorVec_AIS, AIS_InteractiveObject) +public: + + AdaptorVec_AIS() + : myLength (1.0), + myArrowLength (1.0) + {} + + AdaptorVec_AIS (const gp_Pnt& thePnt, + const gp_Dir& theDir, + Standard_Real theLength = 1, + Standard_Real theArrowLength = 1) + : myPnt (thePnt), + myDir (theDir), + myLength (theLength), + myArrowLength (theArrowLength) + { + // + } + + AdaptorVec_AIS (const gp_Pnt& thePnt, + const gp_Vec& theVec, + Standard_Real theArrowLength = 1) + : myPnt (thePnt), + myDir (theVec), + myLength (theVec.Magnitude()), + myArrowLength (theArrowLength) + { + // + } + + AdaptorVec_AIS (const gp_Pnt2d& thePnt2d, + const gp_Dir2d& theDir2d, + Standard_Real theLength = 1, + Standard_Real theArrowLength = 1) + : myPnt (gp_Pnt(thePnt2d.X(), thePnt2d.Y(), 0.0)), + myDir (gp_Dir(theDir2d.X(), theDir2d.Y(), 0.0)), + myLength (theLength), + myArrowLength (theArrowLength) + { + // + } + + AdaptorVec_AIS (const gp_Pnt2d& thePnt2d, + const gp_Vec2d& theVec2d, + Standard_Real theArrowLength = 1) + : myPnt (gp_Pnt(thePnt2d.X(), thePnt2d.Y(), 0.0)), + myDir (gp_Dir(theVec2d.X(), theVec2d.Y(), 0.0)), + myLength (theVec2d.Magnitude()), + myArrowLength (theArrowLength) + { + // + } + + AdaptorVec_AIS (const gp_Pnt2d& thePnt1, + const gp_Pnt2d& thePnt2, + Standard_Real theArrowLength = 1); + + void SetText (const TCollection_AsciiString& theText) + { + myText = theText; + } + + void SetLineAspect (const Handle(Prs3d_LineAspect)& theAspect) + { + myDrawer->SetLineAspect(theAspect); + } + +private: + + //! Return TRUE for supported display modes (only mode 0 is supported). + virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; } + + //! Compute presentation. + virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection (not implemented). + virtual void ComputeSelection (const Handle(SelectMgr_Selection)&, + const Standard_Integer) Standard_OVERRIDE {} + +private: + + gp_Pnt myPnt; + gp_Dir myDir; + Standard_Real myLength; + Standard_Real myArrowLength; + TCollection_AsciiString myText; +}; + +#endif // ADAPTOR_VEC2D_AIS_H diff --git a/samples/OCCTOverview/code/BaseSample.cxx b/samples/OCCTOverview/code/BaseSample.cxx new file mode 100644 index 0000000000..b0aa8d2ce5 --- /dev/null +++ b/samples/OCCTOverview/code/BaseSample.cxx @@ -0,0 +1,185 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "BaseSample.h" + +#include <iostream> +#include <regex> +#include <exception> +#include <stack> + +#include <AIS_ViewCube.hxx> +#include <Message.hxx> +#include <OSD_File.hxx> +#include <OSD_Path.hxx> +#include <OSD_Protection.hxx> + +#include <Standard_WarningsDisable.hxx> +#include <QDir> +#include <Standard_WarningsRestore.hxx> + +const TCollection_AsciiString BaseSample::FILE_EXTENSION = "cxx"; + +void BaseSample::Clear() +{ + myObject3d.Clear(); + myObject2d.Clear(); + myCode.Clear(); + myResult.str(""); +} + +TCollection_AsciiString BaseSample::GetResult() +{ + TCollection_AsciiString aResult(myResult.str().c_str()); + myResult.str(""); + return aResult; +} + +void BaseSample::AppendCube() +{ + Handle(AIS_ViewCube) aViewCube = new AIS_ViewCube(); + myObject3d.Append(aViewCube); +} + +void BaseSample::Process (const TCollection_AsciiString& theSampleName) +{ + myObject3d.Clear(); + myObject2d.Clear(); + myCode.Clear(); + myIsProcessed = Standard_False; + try + { + ExecuteSample(theSampleName); + if (!myObject3d.IsEmpty()) + { + Handle(AIS_ViewCube) aViewCube = new AIS_ViewCube(); + myObject3d.Append(aViewCube); + } + } + catch (...) + { + TraceError(TCollection_AsciiString("Error in sample: ") + theSampleName); + } +} + +void BaseSample::TraceError (const TCollection_AsciiString& theErrorMessage) +{ + Message::SendFail() << "\nERROR: " << theErrorMessage.ToCString() << std::endl; + myResult << "\nERROR: " << theErrorMessage << std::endl; +} + +void BaseSample::FindSourceCode (const TCollection_AsciiString& theSampleName) +{ + TCollection_AsciiString aClassName = DynamicType()->Name(); + char aSeparator = QDir::separator().toLatin1(); + TCollection_AsciiString aCxxFilePach = myCodePath + aSeparator + aClassName + '.' + FILE_EXTENSION; + OSD_File aCxxFile(aCxxFilePach); + try + { + const Standard_Integer aFileBufferSize = 100 * 1024; + TCollection_AsciiString aReadedText(aFileBufferSize); + aCxxFile.Open(OSD_ReadOnly, OSD_Protection()); + aCxxFile.Read(aReadedText, aFileBufferSize); + TCollection_AsciiString aRegexpTemplate = aClassName + "::" + theSampleName + "[\\n\\s]*\\([\\n\\s]*\\)[\\n\\s]*\\{"; + Standard_Integer aOpeningBracketPosition = findEndOfPhrase (aReadedText, aRegexpTemplate); + Standard_Integer aClosingBracketPosition = findClosingBracket (aReadedText, aOpeningBracketPosition, '}'); + myCode = aReadedText.SubString(aOpeningBracketPosition + 1, aClosingBracketPosition - 1); + } + catch (...) + { + TraceError(TCollection_AsciiString("Cannot open file: ") + aCxxFilePach); + } +} + +Standard_Integer BaseSample::findEndOfPhrase (const TCollection_AsciiString& theText, + const TCollection_AsciiString& theRegexpTemplate) +{ + Standard_Integer aIndexOfLastFoundSymbol = -1; + std::string aStdText = theText.ToCString(); + std::string aRegexpTemplate = theRegexpTemplate.ToCString(); + + try + { + std::regex aRegex(theRegexpTemplate.ToCString()); + + std::sregex_iterator aDetectIterator = std::sregex_iterator(aStdText.begin(), aStdText.end(), aRegex); + if (aDetectIterator != std::sregex_iterator()) + { + std::smatch aMatch = *aDetectIterator; + std::string aFoundString = aMatch.str(); + aIndexOfLastFoundSymbol = static_cast<Standard_Integer>(aStdText.find(aFoundString) + aFoundString.length()); + } + else + { + TraceError(TCollection_AsciiString("No code found for template: ") + theRegexpTemplate); + } + } + catch (const std::regex_error& aRegError) + { + TraceError(TCollection_AsciiString("regex_error: ") + aRegError.what()); + } + catch (const std::exception& aEx) + { + TraceError(TCollection_AsciiString("common error: ") + aEx.what()); + } + catch (...) + { + TraceError("unknown error!"); + } + return aIndexOfLastFoundSymbol; +} + +Standard_Integer BaseSample::findClosingBracket (const TCollection_AsciiString& theText, + const Standard_Integer theOpeningBracketIndex, + Standard_Character theClosingBracketSymbol) +{ + // TODO this function not implemented at least 2 cases: + // - brackets in strings & chars + // - brackets in comments + Standard_Integer aClosingBracketIndex = -1; + Standard_Character anOpeningBracketSymbol = theText.Value(theOpeningBracketIndex); + TCollection_AsciiString aBracketsSet(theClosingBracketSymbol); + aBracketsSet += anOpeningBracketSymbol; + Standard_Integer aBracketDepth = 1; + Standard_Integer aStartFindIndex = theOpeningBracketIndex + 1; + //Standard_Character aStartFindChar = theText.Value(aStartFindIndex-1); + while (aBracketDepth) + { + aStartFindIndex = theText.FirstLocationInSet(aBracketsSet, aStartFindIndex, theText.Length()); + if (!aStartFindIndex) + { + TraceError("No closing bracket found!"); + break; + } + TCollection_AsciiString aRSubstr = theText.SubString(aStartFindIndex, theText.Length()); + if (theText.Value(aStartFindIndex) == anOpeningBracketSymbol) + aBracketDepth++; + else if (theText.Value(aStartFindIndex) == theClosingBracketSymbol) + aBracketDepth--; + if (!aBracketDepth) + { + aClosingBracketIndex = aStartFindIndex; + break; + } + aStartFindIndex++; + } + return aClosingBracketIndex; +} diff --git a/samples/OCCTOverview/code/BaseSample.h b/samples/OCCTOverview/code/BaseSample.h new file mode 100644 index 0000000000..20c2470af6 --- /dev/null +++ b/samples/OCCTOverview/code/BaseSample.h @@ -0,0 +1,87 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef BASESAMPLE_H +#define BASESAMPLE_H + +#include <sstream> + +#include <AIS_InteractiveObject.hxx> +#include <NCollection_Vector.hxx> +#include <TCollection_AsciiString.hxx> + +//! Base class for specified category classes +class BaseSample: public Standard_Transient +{ + DEFINE_STANDARD_RTTI_INLINE(BaseSample, Standard_Transient) +public: + BaseSample (const TCollection_AsciiString& theSampleSourcePath, + const Handle(AIS_InteractiveContext)& theContext) + : myCodePath (theSampleSourcePath), + myContext (theContext) + { + // + } + + void Clear(); + void AppendCube(); + + Standard_Boolean IsProcessed() const { return myIsProcessed; } + + const NCollection_Vector<Handle(AIS_InteractiveObject)>& Get2dObjects() const { return myObject2d; } + + const NCollection_Vector<Handle(AIS_InteractiveObject)>& Get3dObjects() const { return myObject3d; } + + TCollection_AsciiString GetResult(); + + TCollection_AsciiString GetCode() const { return myCode; } + + virtual void Process (const TCollection_AsciiString& theSampleName); + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) = 0; + + void FindSourceCode (const TCollection_AsciiString& theSampleName); + void TraceError (const TCollection_AsciiString& theErrorMessage); + +protected: + + Standard_Boolean myIsProcessed; + NCollection_Vector<Handle(AIS_InteractiveObject)> myObject2d; + NCollection_Vector<Handle(AIS_InteractiveObject)> myObject3d; + + std::ostringstream myResult; + TCollection_AsciiString myCode; + TCollection_AsciiString myCodePath; + Handle(AIS_InteractiveContext) myContext; + +protected: + static const TCollection_AsciiString FILE_EXTENSION; + +private: + Standard_Integer findEndOfPhrase (const TCollection_AsciiString& theText, + const TCollection_AsciiString& theRegexpTemplate); + Standard_Integer findClosingBracket (const TCollection_AsciiString& theText, + Standard_Integer theOpeningBracketIndex, + Standard_Character theClosingBracketSymbol); +}; + +#endif //BASESAMPLE_H diff --git a/samples/OCCTOverview/code/DataExchange.json b/samples/OCCTOverview/code/DataExchange.json new file mode 100644 index 0000000000..9d7f444c8f --- /dev/null +++ b/samples/OCCTOverview/code/DataExchange.json @@ -0,0 +1,51 @@ +{ + "Data Exchange": { + "Export": [{ + "text": "BREP", + "function": "BrepExportSample", + "description": "" + }, + { + "text": "STEP", + "function": "StepExportSample", + "description": "" + }, + { + "text": "IGES", + "function": "IgesExportSample", + "description": "" + }, + { + "text": "STL", + "function": "StlExportSample", + "description": "" + }, + { + "text": "VRML", + "function": "VrmlExportSample", + "description": "" + }, + { + "text": "Image", + "function": "ImageExportSample", + "description": "" + } + ], + "Import": [{ + "text": "BREP", + "function": "BrepImportSample", + "description": "" + }, + { + "text": "STEP", + "function": "StepImportSample", + "description": "" + }, + { + "text": "IGES", + "function": "IgesImportSample", + "description": "" + } + ] + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/DataExchangeSamples.cxx b/samples/OCCTOverview/code/DataExchangeSamples.cxx new file mode 100644 index 0000000000..e6bac7356f --- /dev/null +++ b/samples/OCCTOverview/code/DataExchangeSamples.cxx @@ -0,0 +1,410 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "DataExchangeSamples.h" + +#include "MakeBottle.h" + +#include <AIS_ViewCube.hxx> +#include <AIS_Shape.hxx> +#include <BRepTools.hxx> +#include <BRep_Tool.hxx> +#include <BRep_Builder.hxx> +#include <Geom_Surface.hxx> +#include <Geom_Plane.hxx> +#include <Geom_Line.hxx> +#include <Graphic3d_TextureEnv.hxx> +#include <IFSelect_ReturnStatus.hxx> +#include <IGESControl_Controller.hxx> +#include <IGESControl_Reader.hxx> +#include <IGESControl_Writer.hxx> +#include <Interface_Static.hxx> +#include <STEPControl_Reader.hxx> +#include <STEPControl_Writer.hxx> +#include <StlAPI_Writer.hxx> +#include <TopExp_Explorer.hxx> +#include <TopoDS.hxx> +#include <TopoDS_Shape.hxx> +#include <TopoDS_Compound.hxx> +#include <TopTools_HSequenceOfShape.hxx> +#include <VrmlAPI_Writer.hxx> + +void DataExchangeSamples::Process (const TCollection_AsciiString& theSampleName) +{ + if (IsImportSample(theSampleName)) + { + myObject3d.Clear(); + } + myObject2d.Clear(); + myCode.Clear(); + myIsProcessed = Standard_False; + try + { + ExecuteSample(theSampleName); + } + catch (...) + { + TraceError(TCollection_AsciiString("Error in sample: ") + theSampleName); + } +} + +void DataExchangeSamples::AppendBottle() +{ + TopoDS_Shape aBottle = MakeBottle(50, 70, 30); + Handle(AIS_InteractiveObject) aShape = new AIS_Shape(aBottle); + myObject3d.Append(aShape); + Handle(AIS_ViewCube) aViewCube = new AIS_ViewCube(); + myObject3d.Append(aViewCube); + myResult << "A bottle shape was created." << std::endl; +} + +void DataExchangeSamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "BrepExportSample") + { + BrepExportSample(); + } + else if (theSampleName == "StepExportSample") + { + StepExportSample(); + } + else if (theSampleName == "IgesExportSample") + { + IgesExportSample(); + } + else if (theSampleName == "StlExportSample") + { + StlExportSample(); + } + else if (theSampleName == "VrmlExportSample") + { + VrmlExportSample(); + } + else if (theSampleName == "ImageExportSample") + { + ImageExportSample(); + } + else if (theSampleName == "BrepImportSample") + { + BrepImportSample(); + } + else if (theSampleName == "StepImportSample") + { + StepImportSample(); + } + else if (theSampleName == "IgesImportSample") + { + IgesImportSample(); + } + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void DataExchangeSamples::BrepExportSample() +{ + Standard_Boolean anIsShapeExist = Standard_False; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + anIsShapeExist = Standard_True; + if (BRepTools::Write(aShape->Shape(), myFileName.ToCString())) + { + myResult << "A shape was successfully written" << std::endl; + } + else + { + myResult << "A shape was not written" << std::endl; + } + break; // write only one shape + } + } + if (!anIsShapeExist) + { + myResult << "A shape does not exist" << std::endl; + } +} + +void DataExchangeSamples::StepExportSample() +{ + if (myStepType < 0) + { + myResult << "Unknown step type" << std::endl; + return; + } + + IFSelect_ReturnStatus aStatus; + + if (myStepType == STEPControl_FacetedBrep && !CheckFacetedBrep()) + { + myResult << "At least one shape doesn't contain facets" << std::endl; + return; + } + + STEPControl_Writer aStepWriter; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + aStatus = aStepWriter.Transfer(aShape->Shape(), myStepType); + if (aStatus != IFSelect_RetDone) + { + myResult << "A shape was not transferred successfully" << std::endl; + return; + } + } + } + aStatus = aStepWriter.Write(myFileName.ToCString()); + + switch (aStatus) + { + case IFSelect_RetError: + myResult << "Incorrect Data." << std::endl; + break; + case IFSelect_RetFail: + myResult << "Writing error" << std::endl; + break; + case IFSelect_RetVoid: + myResult << "Nothing to transfer." << std::endl; + break; + case IFSelect_RetStop: + case IFSelect_RetDone: + myResult << "A STEP file was successfully written" << std::endl; + break; + } + +} + +void DataExchangeSamples::IgesExportSample() +{ + IGESControl_Controller::Init(); + IGESControl_Writer anIgesWriter(Interface_Static::CVal("XSTEP.iges.unit"), + Interface_Static::IVal("XSTEP.iges.writebrep.mode")); + + Standard_Boolean anIsShapeExist = Standard_False; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + anIsShapeExist = Standard_True; + anIgesWriter.AddShape(aShape->Shape()); + } + } + if (anIsShapeExist) + { + anIgesWriter.ComputeModel(); + if (anIgesWriter.Write(myFileName.ToCString())) + { + myResult << "A STEP file was successfully written" << std::endl; + } + else + { + myResult << "A STEP file was not written" << std::endl; + } + } + else + { + myResult << "Shapes do not exist" << std::endl; + } +} + +void DataExchangeSamples::StlExportSample() +{ + TopoDS_Compound aTopoCompound; + BRep_Builder aBuilder; + aBuilder.MakeCompound(aTopoCompound); + + Standard_Boolean anIsShapeExist = Standard_False; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + anIsShapeExist = Standard_True; + aBuilder.Add(aTopoCompound, aShape->Shape()); + } + } + if (anIsShapeExist) + { + StlAPI_Writer aStlWriter; + if (aStlWriter.Write(aTopoCompound, myFileName.ToCString())) + { + myResult << "A STL file was successfully written" << std::endl; + } + else + { + myResult << "A STL file was not written" << std::endl; + } + } + else + { + myResult << "Shapes do not exist" << std::endl; + } +} + +void DataExchangeSamples::VrmlExportSample() +{ + TopoDS_Compound aTopoCompound; + BRep_Builder aBrepBuilder; + aBrepBuilder.MakeCompound(aTopoCompound); + + Standard_Boolean anIsShapeExist = Standard_False; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + anIsShapeExist = Standard_True; + aBrepBuilder.Add(aTopoCompound, aShape->Shape()); + } + } + if (anIsShapeExist) + { + VrmlAPI_Writer aVrmlWriter; + if (aVrmlWriter.Write(aTopoCompound, myFileName.ToCString())) + { + myResult << "A VRML file was successfully written" << std::endl; + } + else + { + myResult << "A VRML file was not written" << std::endl; + } + } + else + { + myResult << "Shapes do not exist" << std::endl; + } +} + +void DataExchangeSamples::ImageExportSample() +{ + if (myView) + { + Standard_Boolean aResult = myView->Dump(myFileName.ToCString()); + if (aResult) + { + myResult << "An image file was successfully written" << std::endl; + } + else + { + myResult << "An image file was not written" << std::endl; + } + } +} + +void DataExchangeSamples::BrepImportSample() +{ + TopoDS_Shape aTopoShape; + BRep_Builder aBuilder; + Standard_Boolean aResult = BRepTools::Read(aTopoShape, myFileName.ToCString(), aBuilder); + if (aResult) + { + Handle(AIS_Shape) anAisShape = new AIS_Shape(aTopoShape); + myObject3d.Append(anAisShape); + myResult << "A BREP file was read successfully" << std::endl; + } + else + { + myResult << "A BREP file was not read successfully" << std::endl; + } +} + +void DataExchangeSamples::StepImportSample() +{ + Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape(); + STEPControl_Reader aReader; + const IFSelect_ReturnStatus aStatus = aReader.ReadFile(myFileName.ToCString()); + if (aStatus != IFSelect_RetDone) + { + myResult << "A BREP file was not read successfully" << std::endl; + return; + } + + bool anIsFailsOnly = false; + aReader.PrintCheckLoad(anIsFailsOnly, IFSelect_ItemsByEntity); + + int aRootsNumber = aReader.NbRootsForTransfer(); + aReader.PrintCheckTransfer(anIsFailsOnly, IFSelect_ItemsByEntity); + for (Standard_Integer i = 1; i <= aRootsNumber; i++) + { + aReader.TransferRoot(i); + } + + int aShapesNumber = aReader.NbShapes(); + for (int i = 1; i <= aShapesNumber; i++) + { + TopoDS_Shape aTopoShape = aReader.Shape(i); + Handle(AIS_Shape) anAisShape = new AIS_Shape(aTopoShape); + myObject3d.Append(anAisShape); + } + myResult << "A STEP file was read successfully" << std::endl; +} + +void DataExchangeSamples::IgesImportSample() +{ + IGESControl_Reader aReader; + int status = aReader.ReadFile (myFileName.ToCString()); + if (status != IFSelect_RetDone) + { + myResult << "A IGES file was not read successfully" << std::endl; + return; + } + aReader.TransferRoots(); + TopoDS_Shape aTopoShape = aReader.OneShape(); + Handle(AIS_Shape) anAisShape = new AIS_Shape (aTopoShape); + myObject3d.Append(anAisShape); + myResult << "A IGES file was read successfully" << std::endl; +} + +Standard_Boolean DataExchangeSamples::CheckFacetedBrep() +{ + Standard_Boolean anError = Standard_False; + for (Handle(AIS_InteractiveObject) anObject : myObject3d) + { + if (Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anObject)) + { + const TopoDS_Shape aTopoShape = aShape->Shape(); + for (TopExp_Explorer aFaceExplorer(aTopoShape, TopAbs_FACE); aFaceExplorer.More() && !anError; aFaceExplorer.Next()) + { + Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(aFaceExplorer.Current())); + if (!aSurface->IsKind(STANDARD_TYPE(Geom_Plane))) + { + anError = Standard_True; + } + } + for (TopExp_Explorer anEdgeExplorer(aTopoShape, TopAbs_EDGE); anEdgeExplorer.More() && !anError; anEdgeExplorer.Next()) + { + Standard_Real fd, ld; + Handle(Geom_Curve) curve = BRep_Tool::Curve(TopoDS::Edge(anEdgeExplorer.Current()), fd, ld); + if (!curve->IsKind(STANDARD_TYPE(Geom_Line))) + { + anError = Standard_True; + } + } + } + } + return !anError; +} diff --git a/samples/OCCTOverview/code/DataExchangeSamples.h b/samples/OCCTOverview/code/DataExchangeSamples.h new file mode 100644 index 0000000000..548cdcae35 --- /dev/null +++ b/samples/OCCTOverview/code/DataExchangeSamples.h @@ -0,0 +1,90 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef DATAEXCHANGESAMPLES_H +#define DATAEXCHANGESAMPLES_H + +#include "BaseSample.h" + +#include <STEPControl_StepModelType.hxx> +#include <V3d_View.hxx> + +//! Implements Data Exchange samples +class DataExchangeSamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(DataExchangeSamples, BaseSample) +public: + + DataExchangeSamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(V3d_View)& theView, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample (theSampleSourcePath, theContext), + myStepType (STEPControl_StepModelType::STEPControl_AsIs), + myView (theView) + { + // + } + + virtual void Process (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + + void AppendBottle(); + void SetFileName(TCollection_AsciiString theFileName) { myFileName = theFileName; }; + void SetStepType(STEPControl_StepModelType theStepType) { myStepType = theStepType; }; + + static Standard_Boolean IsExportSample(const TCollection_AsciiString& theSampleName) { return theSampleName == "BrepExportSample" + || theSampleName == "StepExportSample" + || theSampleName == "IgesExportSample" + || theSampleName == "StlExportSample" + || theSampleName == "VrmlExportSample" + || theSampleName == "ImageExportSample"; } + static Standard_Boolean IsImportSample(const TCollection_AsciiString& theSampleName) { return theSampleName == "BrepImportSample" + || theSampleName == "StepImportSample" + || theSampleName == "IgesImportSample"; } + static Standard_Boolean IsBrepSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "BrepExportSample" || theSampleName == "BrepImportSample"; } + static Standard_Boolean IsStepSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "StepExportSample" || theSampleName == "StepImportSample"; } + static Standard_Boolean IsIgesSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "IgesExportSample" || theSampleName == "IgesImportSample"; } + static Standard_Boolean IsStlSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "StlExportSample"; } + static Standard_Boolean IsVrmlSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "VrmlExportSample"; } + static Standard_Boolean IsImageSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "ImageExportSample"; } + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + TCollection_AsciiString myFileName; + STEPControl_StepModelType myStepType; + Handle(V3d_View) myView; + +private: + Standard_Boolean CheckFacetedBrep(); + // One function for every sample + void BrepExportSample(); + void StepExportSample(); + void IgesExportSample(); + void StlExportSample(); + void VrmlExportSample(); + void ImageExportSample(); + void BrepImportSample(); + void StepImportSample(); + void IgesImportSample(); +}; + +#endif //DATAEXCHANGESAMPLES_H diff --git a/samples/OCCTOverview/code/FILES b/samples/OCCTOverview/code/FILES new file mode 100644 index 0000000000..f0f05d2184 --- /dev/null +++ b/samples/OCCTOverview/code/FILES @@ -0,0 +1,48 @@ +AdaptorCurve2d_AIS.cxx +AdaptorCurve2d_AIS.h +AdaptorCurve_AIS.cxx +AdaptorCurve_AIS.h +AdaptorPnt2d_AIS.cxx +AdaptorPnt2d_AIS.h +AdaptorVec_AIS.cxx +AdaptorVec_AIS.h +BaseSample.cxx +BaseSample.h +DataExchange.json +DataExchangeSamples.cxx +DataExchangeSamples.h +Geometry.json +GeometrySamples.cxx +GeometrySamples.h +MakeBottle.cxx +MakeBottle.h +Ocaf.json +OcafSamples.cxx +OcafSamples.h +Sample2D_Face.cxx +Sample2D_Face.h +Sample2D_Image.cxx +Sample2D_Image.h +Sample2D_Markers.cxx +Sample2D_Markers.h +Samples.qrc +TOcafFunction_BoxDriver.cxx +TOcafFunction_BoxDriver.h +TOcafFunction_CutDriver.cxx +TOcafFunction_CutDriver.h +TOcafFunction_CylDriver.cxx +TOcafFunction_CylDriver.h +TOcaf_Application.cxx +TOcaf_Application.h +Topology.json +TopologySamples.cxx +TopologySamples.h +Triangulation.json +TriangulationSamples.cxx +TriangulationSamples.h +Viewer2d.json +Viewer2dSamples.cxx +Viewer2dSamples.h +Viewer3d.json +Viewer3dSamples.cxx +Viewer3dSamples.h diff --git a/samples/OCCTOverview/code/Geometry.json b/samples/OCCTOverview/code/Geometry.json new file mode 100644 index 0000000000..1e2d6821de --- /dev/null +++ b/samples/OCCTOverview/code/Geometry.json @@ -0,0 +1,287 @@ +{ + "Non Parametric": { + "Free creating": { + "3D": [{ + "text": "Zero Dimension objects", + "function": "ZeroDimensionObjects3dSample", + "description": "" + }, + { + "text": "Vectors", + "function": "Vectors3dSample", + "description": "" + }, + { + "text": "Infinity lines", + "function": "InfinityLines3dSample", + "description": "" + }, + { + "text": "Second order curves", + "function": "SecondOrderCurves3dSample", + "description": "" + }, + { + "text": "Plane surfaces", + "function": "PlaneSurfaces3dSample", + "description": "" + }, + { + "text": "Second order surfaces", + "function": "SecondOrderSurfaces3dSample", + "description": "" + } + ], + "2D": [{ + "text": "Zero Dimension objects", + "function": "ZeroDimensionObjects2dSample", + "description": "" + }, + { + "text": "Vectors", + "function": "Vectors2dSample", + "description": "" + }, + { + "text": "Infinity lines", + "function": "InfinityLines2dSample", + "description": "" + }, + { + "text": "Second order curves", + "function": "SecondOrderCurves2dSample", + "description": "" + } + ] + } + + , + "Creating based on criteria": { + "3D": [{ + "text": "Barycenter point", + "function": "BarycenterPoint3dSample", + "description": "" + }, + { + "text": "Rotated vector", + "function": "RotatedVector3dSample", + "description": "" + }, + { + "text": "Mirrored line", + "function": "MirroredLine3dSample", + "description": "" + }, + { + "text": "Scaled Ellipse", + "function": "ScaledEllipse3dSample", + "description": "" + }, + { + "text": "Transformed cylinder", + "function": "TransformedCylinder3dSample", + "description": "" + }, + { + "text": "Translated torus", + "function": "TranslatedTorus3dSample", + "description": "" + }, + { + "text": "Conjugate objects ", + "function": "ConjugateObjects3dSample", + "description": "" + }, + { + "text": "Projection of point", + "function": "ProjectionOfPoint3dSample", + "description": "" + }, + { + "text": "Minimal distance", + "function": "MinimalDistance3dSample", + "description": "" + }, + { + "text": "Intersection", + "function": "Intersection3dSample", + "description": "" + } + ], + "2D": [{ + "text": "Translated point", + "function": "TranslatedPoint2dSample", + "description": "" + }, + { + "text": "Rotated direction", + "function": "RotatedDirection2dSample", + "description": "" + }, + { + "text": "Mirrored axis", + "function": "MirroredAxis2dSample", + "description": "" + }, + { + "text": "Transformed ellipse", + "function": "TransformedEllipse2dSample", + "description": "" + }, + { + "text": "Conjugate objects", + "function": "ConjugateObjects2dSample", + "description": "" + }, + { + "text": "Tangent to 2 cilcles", + "function": "Tangent2dSample", + "description": "" + }, + { + "text": "Projection of point", + "function": "ProjectionOfPoint2dSample", + "description": "" + }, + { + "text": "Minimal distance", + "function": "MinimalDistance2dSample", + "description": "" + }, + { + "text": "Intersection", + "function": "Intersection2dSample", + "description": "" + } + ] + }, + "Data extraction": { + "3D": [{ + "text": "Point info", + "function": "PointInfo3dSample", + "description": "" + }, + { + "text": "Ellipse info", + "function": "EllipseInfo3dSample", + "description": "" + } + ], + "2D": [{ + "text": "Point info", + "function": "PointInfo2dSample", + "description": "" + }, + { + "text": "Circle info", + "function": "CircleInfo2dSample", + "description": "" + } + ] + } + + }, + "Parametric": { + "Free creating": { + "3D": [{ + "text": "Free style curves", + "function": "FreeStyleCurves3dSample", + "description": "" + }, + { + "text": "Analytical surfaces", + "function": "AnalyticalSurfaces3dSample", + "description": "" + }, + { + "text": "Free style surfaces", + "function": "FreeStyleSurfaces3dSample", + "description": "" + } + ], + "2D": [{ + "text": "Free style curves", + "function": "FreeStyleCurves2dSample", + "description": "" + } + ] + }, + "Creating based on geometry": { + "3D": [{ + "text": "Trimmed curve", + "function": "TrimmedCurve3dSample", + "description": "" + }, + { + "text": "Offset curve", + "function": "OffsetCurve3dSample", + "description": "" + }, + { + "text": "BSpline from circle", + "function": "BSplineFromCircle3dSample", + "description": "" + }, + { + "text": "Trimmed surface", + "function": "TrimmedSurface3dSample", + "description": "" + }, + { + "text": "Offset surface", + "function": "OffsetSurface3dSample", + "description": "" + }, + { + "text": "Extrusion surface", + "function": "ExtrusionSurface3dSample", + "description": "" + }, + { + "text": "Revolution surface", + "function": "RevolutionSurface3dSample", + "description": "" + } + ], + "2D": [{ + "text": "Trimmed curve", + "function": "TrimmedCurve2dSample", + "description": "" + }, + { + "text": "Offset curve", + "function": "OffsetCurve2dSample", + "description": "" + } + ] + }, + "Extract geometry": [{ + "text": "Bounding box of surface (3D)", + "function": "BoundingBoxOfSurface3dSample", + "description": "" + }, + { + "text": "Bounding box of curves (3D)", + "function": "BoundingBoxOfCurves3dSample", + "description": "" + }, + { + "text": "Bounding box of curves (2D)", + "function": "BoundingBoxOfCurves2dSample", + "description": "" + } + ], + "Data extraction": [{ + "text": "Dump circle info", + "function": "DumpCircleInfoSample", + "description": "" + }, + { + "text": "Dump BSpline curve info", + "function": "DumpBSplineCurveInfoSample", + "description": "" + } + ] + + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/GeometrySamples.cxx b/samples/OCCTOverview/code/GeometrySamples.cxx new file mode 100644 index 0000000000..278e5e1089 --- /dev/null +++ b/samples/OCCTOverview/code/GeometrySamples.cxx @@ -0,0 +1,2027 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "GeometrySamples.h" + +#include <limits> + +#include <gp_Pnt.hxx> +#include <gp_XYZ.hxx> +#include <gp_Vec.hxx> +#include <gp_Dir.hxx> +#include <gp_Ax1.hxx> +#include <gp_Ax2.hxx> +#include <gp_Ax3.hxx> +#include <gp_Lin.hxx> +#include <gp_Circ.hxx> +#include <gp_Elips.hxx> +#include <gp_Parab.hxx> +#include <gp_Hypr.hxx> +#include <gp_Cylinder.hxx> +#include <gp_Cone.hxx> +#include <gp_Sphere.hxx> +#include <gp_Torus.hxx> + +#include <gp_Pnt2d.hxx> +#include <gp_XY.hxx> +#include <gp_Ax2d.hxx> +#include <gp_Ax22d.hxx> +#include <gp_Lin2d.hxx> +#include <gp_Circ2d.hxx> +#include <gp_Elips2d.hxx> +#include <gp_Parab2d.hxx> +#include <gp_Hypr2d.hxx> +#include <Geom2d_BSplineCurve.hxx> +#include <Geom2d_BezierCurve.hxx> +#include <Geom2d_OffsetCurve.hxx> +#include <ProjLib.hxx> +#include <ElSLib.hxx> +#include <Extrema_ExtElCS.hxx> +#include <Extrema_POnCurv.hxx> +#include <IntAna_Quadric.hxx> +#include <IntAna_IntConicQuad.hxx> +#include <GccAna_Lin2d2Tan.hxx> +#include <GccEnt_QualifiedCirc.hxx> +#include <Geom2dAPI_ProjectPointOnCurve.hxx> +#include <Geom2dAPI_ExtremaCurveCurve.hxx> +#include <Geom2dAPI_InterCurveCurve.hxx> +#include <Geom2dAPI_PointsToBSpline.hxx> + +#include <Geom_CartesianPoint.hxx> +#include <Geom_VectorWithMagnitude.hxx> +#include <Geom_Axis1Placement.hxx> +#include <Geom_Axis2Placement.hxx> +#include <Geom_Line.hxx> +#include <Geom_Circle.hxx> +#include <Geom_Ellipse.hxx> +#include <Geom_Parabola.hxx> +#include <Geom_Hyperbola.hxx> +#include <Geom_BSplineCurve.hxx> +#include <Geom_BezierCurve.hxx> +#include <Geom_TrimmedCurve.hxx> +#include <Geom_OffsetCurve.hxx> +#include <Geom_BSplineSurface.hxx> +#include <Geom_BezierSurface.hxx> +#include <Geom_Plane.hxx> +#include <Geom_CylindricalSurface.hxx> +#include <Geom_ConicalSurface.hxx> +#include <Geom_SphericalSurface.hxx> +#include <Geom_ToroidalSurface.hxx> +#include <Geom_RectangularTrimmedSurface.hxx> +#include <Geom_OffsetSurface.hxx> +#include <Geom_SurfaceOfLinearExtrusion.hxx> +#include <Geom_SurfaceOfRevolution.hxx> + +#include <BndLib_Add3dCurve.hxx> +#include <BndLib_AddSurface.hxx> +#include <GeomAdaptor_Curve.hxx> +#include <GeomAdaptor_Surface.hxx> +#include <GeomAPI_PointsToBSpline.hxx> +#include <GeomAPI_PointsToBSplineSurface.hxx> +#include <GeomConvert.hxx> + +#include "AdaptorPnt2d_AIS.h" +#include "AdaptorVec_AIS.h" +#include "AdaptorCurve_AIS.h" +#include "AdaptorCurve2d_AIS.h" + +#include <Geom2d_CartesianPoint.hxx> +#include <Geom2d_VectorWithMagnitude.hxx> +#include <Geom2d_Line.hxx> +#include <Geom2d_Circle.hxx> +#include <Geom2d_Ellipse.hxx> +#include <Geom2d_Parabola.hxx> +#include <Geom2d_Hyperbola.hxx> +#include <Geom2d_TrimmedCurve.hxx> +#include <Geom2dAdaptor_Curve.hxx> +#include <Bnd_Box2d.hxx> +#include <BndLib_Add2dCurve.hxx> +#include <Adaptor2d_Curve2d.hxx> + +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <BRepBuilderAPI_MakeFace.hxx> +#include <BRepPrimAPI_MakeBox.hxx> + +#include <AIS_Point.hxx> +#include <AIS_TextLabel.hxx> +#include <AIS_Axis.hxx> +#include <AIS_InteractiveContext.hxx> +#include <AIS_Circle.hxx> +#include <AIS_Plane.hxx> +#include <AIS_Shape.hxx> +#include <AIS_ColoredShape.hxx> + +#include <GProp_PEquation.hxx> + +void GeometrySamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "ZeroDimensionObjects3dSample") + ZeroDimensionObjects3dSample(); + else if (theSampleName == "Vectors3dSample") + Vectors3dSample(); + else if (theSampleName == "InfinityLines3dSample") + InfinityLines3dSample(); + else if (theSampleName == "SecondOrderCurves3dSample") + SecondOrderCurves3dSample(); + else if (theSampleName == "PlaneSurfaces3dSample") + PlaneSurfaces3dSample(); + else if (theSampleName == "SecondOrderSurfaces3dSample") + SecondOrderSurfaces3dSample(); + else if (theSampleName == "ZeroDimensionObjects2dSample") + ZeroDimensionObjects2dSample(); + else if (theSampleName == "Vectors2dSample") + Vectors2dSample(); + else if (theSampleName == "InfinityLines2dSample") + InfinityLines2dSample(); + else if (theSampleName == "SecondOrderCurves2dSample") + SecondOrderCurves2dSample(); + else if (theSampleName == "BarycenterPoint3dSample") + BarycenterPoint3dSample(); + else if (theSampleName == "RotatedVector3dSample") + RotatedVector3dSample(); + else if (theSampleName == "MirroredLine3dSample") + MirroredLine3dSample(); + else if (theSampleName == "ScaledEllipse3dSample") + ScaledEllipse3dSample(); + else if (theSampleName == "TransformedCylinder3dSample") + TransformedCylinder3dSample(); + else if (theSampleName == "TranslatedTorus3dSample") + TranslatedTorus3dSample(); + else if (theSampleName == "ConjugateObjects3dSample") + ConjugateObjects3dSample(); + else if (theSampleName == "ProjectionOfPoint3dSample") + ProjectionOfPoint3dSample(); + else if (theSampleName == "MinimalDistance3dSample") + MinimalDistance3dSample(); + else if (theSampleName == "MirroredAxis2dSample") + MirroredAxis2dSample(); + else if (theSampleName == "TransformedEllipse2dSample") + TransformedEllipse2dSample(); + else if (theSampleName == "ConjugateObjects2dSample") + ConjugateObjects2dSample(); + else if (theSampleName == "Intersection3dSample") + Intersection3dSample(); + else if (theSampleName == "TranslatedPoint2dSample") + TranslatedPoint2dSample(); + else if (theSampleName == "RotatedDirection2dSample") + RotatedDirection2dSample(); + else if (theSampleName == "Tangent2dSample") + Tangent2dSample(); + else if (theSampleName == "ProjectionOfPoint2dSample") + ProjectionOfPoint2dSample(); + else if (theSampleName == "MinimalDistance2dSample") + MinimalDistance2dSample(); + else if (theSampleName == "Intersection2dSample") + Intersection2dSample(); + else if (theSampleName == "PointInfo3dSample") + PointInfo3dSample(); + else if (theSampleName == "EllipseInfo3dSample") + EllipseInfo3dSample(); + else if (theSampleName == "PointInfo2dSample") + PointInfo2dSample(); + else if (theSampleName == "CircleInfo2dSample") + CircleInfo2dSample(); + else if (theSampleName == "SecondOrderCurves3dSample") + SecondOrderCurves3dSample(); + else if (theSampleName == "FreeStyleCurves3dSample") + FreeStyleCurves3dSample(); + else if (theSampleName == "AnalyticalSurfaces3dSample") + AnalyticalSurfaces3dSample(); + else if (theSampleName == "FreeStyleSurfaces3dSample") + FreeStyleSurfaces3dSample(); + else if (theSampleName == "SecondOrderCurves2dSample") + SecondOrderCurves2dSample(); + else if (theSampleName == "FreeStyleCurves2dSample") + FreeStyleCurves2dSample(); + else if (theSampleName == "TrimmedCurve3dSample") + TrimmedCurve3dSample(); + else if (theSampleName == "OffsetCurve3dSample") + OffsetCurve3dSample(); + else if (theSampleName == "BSplineFromCircle3dSample") + BSplineFromCircle3dSample(); + else if (theSampleName == "TrimmedSurface3dSample") + TrimmedSurface3dSample(); + else if (theSampleName == "OffsetSurface3dSample") + OffsetSurface3dSample(); + else if (theSampleName == "ExtrusionSurface3dSample") + ExtrusionSurface3dSample(); + else if (theSampleName == "RevolutionSurface3dSample") + RevolutionSurface3dSample(); + else if (theSampleName == "TrimmedCurve2dSample") + TrimmedCurve2dSample(); + else if (theSampleName == "OffsetCurve2dSample") + OffsetCurve2dSample(); + else if (theSampleName == "BoundingBoxOfSurface3dSample") + BoundingBoxOfSurface3dSample(); + else if (theSampleName == "BoundingBoxOfCurves3dSample") + BoundingBoxOfCurves3dSample(); + else if (theSampleName == "BoundingBoxOfCurves2dSample") + BoundingBoxOfCurves2dSample(); + else if (theSampleName == "DumpCircleInfoSample") + DumpCircleInfoSample(); + else if (theSampleName == "DumpBSplineCurveInfoSample") + DumpBSplineCurveInfoSample(); + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void GeometrySamples::DisplayPnt (const gp_Pnt2d& thePnt2d, const TCollection_AsciiString& theText, + Aspect_TypeOfMarker theMarker, Standard_Real theDistance) +{ + gp_Pnt aPnt(thePnt2d.X(), thePnt2d.Y(), 0.0); + Handle(Geom_CartesianPoint) aGeomPoint = new Geom_CartesianPoint(aPnt); + Handle(AIS_Point) anAisPoint = new AIS_Point(aGeomPoint); + anAisPoint->SetMarker(theMarker); + myObject2d.Append(anAisPoint); + Handle(AIS_TextLabel) aPntLabel = new AIS_TextLabel(); + aPntLabel->SetText(theText); + aPntLabel->SetPosition(gp_Pnt(aPnt.X(), aPnt.Y() + theDistance, aPnt.Z())); + myObject2d.Append(aPntLabel); +} +void GeometrySamples::DisplayPnt (const gp_Pnt& thePnt, const TCollection_AsciiString& theText, + Aspect_TypeOfMarker theMarker, Standard_Real theDistance) +{ + Handle(Geom_CartesianPoint) aPoint = new Geom_CartesianPoint(thePnt); + Handle(AIS_Point) anAisPoint = new AIS_Point(aPoint); + anAisPoint->SetMarker(theMarker); + myObject3d.Append(anAisPoint); + Handle(AIS_TextLabel) aPntLabel = new AIS_TextLabel(); + aPntLabel->SetText(theText); + aPntLabel->SetPosition(gp_Pnt(thePnt.X(), thePnt.Y(), thePnt.Z() + theDistance)); + myObject3d.Append(aPntLabel); +} + +void GeometrySamples::ZeroDimensionObjects3dSample() +{ + // gp_Pnt describes a point in 3D space. A Geom_CartesianPoint is defined by + // a gp_Pnt point, with its three Cartesian coordinates X, Y and Z. + gp_Pnt aCoordPnt(10.0, 20.0, 30.0); + Handle(Geom_CartesianPoint) aCoordGeomPoint = new Geom_CartesianPoint(aCoordPnt); + Handle(AIS_Point) aCoordAisPoint = new AIS_Point(aCoordGeomPoint); + myObject3d.Append(aCoordAisPoint); + + Handle(AIS_TextLabel) aPntLabel = new AIS_TextLabel(); + aPntLabel->SetText(" gp_Pnt"); + aPntLabel->SetPosition(gp_Pnt(aCoordPnt.X(), aCoordPnt.Y(), aCoordPnt.Z() + 5.0)); + myObject3d.Append(aPntLabel); + myResult << "gp_Pnt was created" << std::endl; + + // gp_XYZ class describes a Cartesian coordinate entity in 3D space (X,Y,Z). + // This entity is used for algebraic calculation. + // This entity can be transformed with a "Trsf" or a "GTrsf" from package "gp". + // It is used in vectorial computations or for holding this type of information + // in data structures. + gp_XYZ aXyz1(10.0, 20.0, 30.0); + gp_XYZ aXyz2(20.0, 10.0, 30.0); + gp_XYZ aXyzSum = aXyz1 + aXyz2; + gp_Pnt aSumPnt(aXyzSum); + Handle(Geom_CartesianPoint) aXyzGeomPoint = new Geom_CartesianPoint(aSumPnt); + Handle(AIS_Point) aSumAisPoint = new AIS_Point(aXyzGeomPoint); + myObject3d.Append(aSumAisPoint); + + Handle(AIS_TextLabel) aXyzLabel = new AIS_TextLabel(); + aXyzLabel->SetText(" gp_XYZ"); + aXyzLabel->SetPosition(gp_Pnt(aXyzSum.X(), aXyzSum.Y(), aXyzSum.Z() + 5.0)); + myObject3d.Append(aXyzLabel); + myResult << "gp_XYZ was created" << std::endl; +} + +void GeometrySamples::Vectors3dSample() +{ + gp_Pnt aPnt1(0.0, 0.0, 0.0); + gp_Pnt aPnt2(5.0, 0.0, 0.0); + + // gp_Vec defines a non-persistent vector in 3D space. + gp_Vec aVec(aPnt1, aPnt2); + Handle(AdaptorVec_AIS) aVecAIS = new AdaptorVec_AIS(aPnt1, aVec, 0.5); + aVecAIS->SetText(" gp_Vec"); + myObject3d.Append(aVecAIS); + myResult << "gp_Vec magnitude: " << aVec.Magnitude() << std::endl; + + // Describes a unit vector in 3D space. + // This unit vector is also called "Direction". + // See Also gce_MakeDir which provides functions for more complex unit vector + // constructions Geom_Direction which provides additional functions + // for constructing unit vectors and works, in particular, + // with the parametric equations of unit vectors. + gp_Dir aDir(aVec); + Handle(AdaptorVec_AIS) aDirAIS = new AdaptorVec_AIS(gp_Pnt(0.0, 0.0, 10.0), aDir, 1.0, 0.5); + aDirAIS->SetText(" gp_Dir"); + myObject3d.Append(aDirAIS); + myResult << "gp_Dir coordinates: X: " << aDir.X() << ", Y: " << aDir.Y() << ", Z: " << aDir.Z() << std::endl; +} + +void GeometrySamples::InfinityLines3dSample() +{ + gp_Pnt aBasePoint(0.0, 0.0, 0.0); + gp_Dir aX_Direction(1.0, 0.0, 0.0); + gp_Dir anY_Direction(0.0, 1.0, 0.0); + gp_Dir aZ_Direction(0.0, 0.0, 1.0); + + // Describes an axis in 3D space. + gp_Ax1 anAxis1(aBasePoint, aZ_Direction); + Handle(AdaptorVec_AIS) anAx1Ais = new AdaptorVec_AIS(anAxis1.Location(), anAxis1.Direction(), 1.0, 0.3); + anAx1Ais->SetText(" gp_Ax1"); + myObject3d.Append(anAx1Ais); + myResult << "gp_Ax1 was created" << std::endl << std::endl; + + // Describes a right - handed coordinate system in 3D space. + aBasePoint.SetCoord(0.0, 0.0, 3.0); + gp_Ax2 anAxis2(aBasePoint, aZ_Direction); + Handle(AdaptorVec_AIS) aAx2AisZ = new AdaptorVec_AIS(anAxis2.Location(), anAxis2.Direction(), 1.0, 0.3); + aAx2AisZ->SetText(" gp_Ax2 Z"); + myObject3d.Append(aAx2AisZ); + Handle(AdaptorVec_AIS) aAx2AisX = new AdaptorVec_AIS(anAxis2.Location(), anAxis2.XDirection(), 1.0, 0.3); + aAx2AisX->SetText(" gp_Ax2 X"); + myObject3d.Append(aAx2AisX); + Handle(AdaptorVec_AIS) aAx2AisY = new AdaptorVec_AIS(anAxis2.Location(), anAxis2.YDirection(), 1.0, 0.3); + aAx2AisY->SetText(" gp_Ax2 Y"); + myObject3d.Append(aAx2AisY); + myResult << "gp_Ax2 was created" << std::endl; + + // Describes a coordinate system in 3D space.Unlike a gp_Ax2 coordinate system, + // a gp_Ax3 can be right - handed("direct sense") or left - handed("indirect sense"). + gp_Ax3 anAxis3(gp_XYZ(0.0, 0.0, 6.0), aZ_Direction, aX_Direction); + anAxis3.YReverse(); + Handle(AdaptorVec_AIS) anAx3AisZ = new AdaptorVec_AIS(anAxis3.Location(), anAxis3.Direction(), 1.0, 0.3); + anAx3AisZ->SetText(" gp_Ax3 Z"); + myObject3d.Append(anAx3AisZ); + Handle(AdaptorVec_AIS) anAx3AisX = new AdaptorVec_AIS(anAxis3.Location(), anAxis3.XDirection(), 1.0, 0.3); + anAx3AisX->SetText(" gp_Ax3 X"); + myObject3d.Append(anAx3AisX); + Handle(AdaptorVec_AIS) anAx3AisY = new AdaptorVec_AIS(anAxis3.Location(), anAxis3.YDirection(), 1.0, 0.3); + anAx3AisY->SetText(" gp_Ax3 Y"); + myObject3d.Append(anAx3AisY); + + myResult << "gp_Ax3 was created" << std::endl; + const gp_Dir& anAxis3_xDir = anAxis3.XDirection(); + const gp_Dir& anAxis3_yDir = anAxis3.YDirection(); + myResult << "gp_Ax3 X direction: " << anAxis3_xDir.X() << " " << anAxis3_xDir.Y() << " " << anAxis3_xDir.Z() << std::endl; + myResult << "gp_Ax3 Y direction: " << anAxis3_yDir.X() << " " << anAxis3_yDir.Y() << " " << anAxis3_yDir.Z() << std::endl; + TCollection_AsciiString aDirectionDescription; + if (anAxis3.Direct()) + { + aDirectionDescription = "anAxis3 is a right-handed axis system"; + } + else + { + aDirectionDescription = "anAxis3 is a left-handed axis system"; + } + myResult << aDirectionDescription << std::endl << std::endl; + + // Describes a line in 3D space. A line is positioned in space with an axis + // (a gp_Ax1 object) which gives it an origin and a unit vector. + gp_Lin aLine(gp_Pnt(5.0, 0.0, 0.0), gp_Dir(0.0, 1.0, 0.0)); + Handle(AdaptorVec_AIS) anLineAis = new AdaptorVec_AIS(aLine.Location(), aLine.Direction(), 8.0); + anLineAis->SetText(" gp_Lin"); + myObject3d.Append(anLineAis); + myResult << "gp_Lin was created" << std::endl << std::endl; +} + +void GeometrySamples::SecondOrderCurves3dSample() +{ + gp_Ax2 anAxis2(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)); + gp_Circ aCirc(anAxis2, 10.0); + Handle(Geom_Circle) aGeomCircle = new Geom_Circle(aCirc); + Handle(AIS_Circle) anAisCircle = new AIS_Circle(aGeomCircle); + myObject3d.Append(anAisCircle); + + // Describes an ellipse in 3D space. An ellipse is defined by its major and minor + // radii and positioned in space with a coordinate system (a gp_Ax2 object) + gp_Elips anElips(anAxis2.Translated(gp_Vec(0.0, 0.0, 10.0)), 20.0, 10.0); + Handle(Geom_Ellipse) aGeomEllipse = new Geom_Ellipse(anElips); + Handle(AdaptorCurve_AIS) anAisEllipce = new AdaptorCurve_AIS(aGeomEllipse); + myObject3d.Append(anAisEllipce); + + // Describes a parabola in 3D space. A parabola is defined by its focal length + // (that is, the distance between its focus and apex) and positioned in space with + // a coordinate system (a gp_Ax2 object) + gp_Parab aParab(anAxis2.Translated(gp_Vec(0.0, 0.0, 20.0)), 2.0); + Handle(Geom_Parabola) aGeomParabola = new Geom_Parabola(aParab); + Handle(Geom_TrimmedCurve) aTrimmedParabola = new Geom_TrimmedCurve(aGeomParabola, 20.0, -20.0); + Handle(AdaptorCurve_AIS) anAisParabola = new AdaptorCurve_AIS(aTrimmedParabola); + myObject3d.Append(anAisParabola); + + // Describes a branch of a hyperbola in 3D space. A hyperbola is defined by its major + // and minor radii and positioned in space with a coordinate system (a gp_Ax2 object) + gp_Hypr aHypr(anAxis2.Translated(gp_Vec(0.0, 0.0, 30.0)), 20.0, 10.0); + Handle(Geom_Hyperbola) aGeomHyperbola = new Geom_Hyperbola(aHypr); + Handle(Geom_TrimmedCurve) aTrimmedHyperbola = new Geom_TrimmedCurve(aGeomHyperbola, 2.0, -2.0); + Handle(AdaptorCurve_AIS) anAisHyperbola = new AdaptorCurve_AIS(aTrimmedHyperbola); + myObject3d.Append(anAisHyperbola); +} + +void GeometrySamples::PlaneSurfaces3dSample() +{ + // Describes a plane.A plane is positioned in space with a coordinate system(a gp_Ax3 object), + // such that the plane is defined by the origin, "X Direction" and "Y Direction" of this + // coordinate system, which is the "local coordinate system" of the plane.The "main Direction" + // of the coordinate system is a vector normal to the plane. + gp_Pln aPln(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)); + Handle(Geom_Plane) aPlane = new Geom_Plane(aPln); + Handle(AIS_Plane) anAisPlane = new AIS_Plane(aPlane, aPln.Location(), + gp_Pnt(10.0, 10.0, 0.0), + gp_Pnt(-10.0, -10.0, 0.0), + Standard_False); + myObject3d.Append(anAisPlane); + + // Describes an infinite cylindrical surface.A cylinder is defined by its radius and positioned + // in space with a coordinate system(a gp_Ax3 object), the "main Axis" of which is the axis of + // the cylinder.This coordinate system is the "local coordinate system" of the cylinder. + gp_Cylinder aCylinder(gp_Ax3(gp_Pnt(0.0, 0.0, 10.0), gp_Dir(0.0, 0.0, 1.0)), 10.0); + Handle(Geom_CylindricalSurface) aCylindricalSurface = new Geom_CylindricalSurface(aCylinder); + Handle(AIS_Shape) anAisCylinder = new AIS_Shape(BRepBuilderAPI_MakeFace( + aCylindricalSurface, 0.0, 2.0*M_PI, 0.0, 10.0, Precision::Confusion()).Shape()); + myObject3d.Append(anAisCylinder); + + // Defines an infinite conical surface. A cone is defined by its half-angle (can be negative) at + // the apex and positioned in space with a coordinate system (a gp_Ax3 object) and a "reference radius" + gp_Cone aCone(gp_Ax3(gp_Pnt(0.0, 0.0, 30.0), gp_Dir(0.0, 0.0, 1.0)), 0.25*M_PI, 0.0); + Handle(Geom_ConicalSurface) aConicalSurface = new Geom_ConicalSurface(aCone); + Handle(AIS_Shape) anAisCone = new AIS_Shape(BRepBuilderAPI_MakeFace( + aConicalSurface, 0.0, 2.0*M_PI, 0.0, 20.0, Precision::Confusion()).Shape()); + myObject3d.Append(anAisCone); +} + +void GeometrySamples::SecondOrderSurfaces3dSample() +{ + gp_Sphere aSphere(gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)), 10.0); + Handle(Geom_SphericalSurface) aSphericalSurface = new Geom_SphericalSurface(aSphere); + Handle(AIS_Shape) anAisSphere = new AIS_Shape(BRepBuilderAPI_MakeFace( + aSphericalSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisSphere); + + gp_Torus aTorus(gp_Ax3(gp_Pnt(0.0, 0.0, 20.0), gp_Dir(0.0, 0.0, 1.0)), 40.0, 10.0); + Handle(Geom_ToroidalSurface) aToroidalSurface = new Geom_ToroidalSurface(aTorus); + Handle(AIS_Shape) anAisTorus = new AIS_Shape(BRepBuilderAPI_MakeFace( + aToroidalSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisTorus); +} + +void GeometrySamples::ZeroDimensionObjects2dSample() +{ + // Defines a non-persistent 2D Cartesian point. + gp_Pnt2d aCoordPnt(10.0, 20.0); + Handle(Geom2d_CartesianPoint) aCoordGeomPoint = new Geom2d_CartesianPoint(aCoordPnt); + Handle(AdaptorPnt2d_AIS) aCoordAisPoint = new AdaptorPnt2d_AIS(aCoordGeomPoint); + myObject2d.Append(aCoordAisPoint); + + Handle(AIS_TextLabel) aPntLabel = new AIS_TextLabel(); + aPntLabel->SetText("gp_Pnt2d"); + aPntLabel->SetPosition(gp_Pnt(aCoordPnt.X(), aCoordPnt.Y() + 0.5, 0.0)); + myObject2d.Append(aPntLabel); + myResult << "gp_Pnt was created" << std::endl; + + // This class describes a Cartesian coordinate entity in 2D space{ X,Y }. + // This class is non persistent.This entity used for algebraic calculation. + // An XY can be transformed with a Trsf2d or a GTrsf2d from package gp. + // It is used in vectorial computations or for holding this type of information in data structures. + gp_XY aXy(20.0, 10.0); + Handle(Geom2d_CartesianPoint) aXyGeomPoint = new Geom2d_CartesianPoint(aXy); + Handle(AdaptorPnt2d_AIS) aXyAisPoint = new AdaptorPnt2d_AIS(aXyGeomPoint); + myObject2d.Append(aXyAisPoint); + + Handle(AIS_TextLabel) aXyLabel = new AIS_TextLabel(); + aXyLabel->SetText(" gp_XY"); + aXyLabel->SetPosition(gp_Pnt(aXy.X(), aXy.Y() + 0.5, 0.0)); + myObject2d.Append(aXyLabel); + myResult << "gp_XY was created" << std::endl; +} + +void GeometrySamples::Vectors2dSample() +{ + // Describes a unit vector in the plane (2D space). + // This unit vector is also called "Direction". + gp_Dir2d aDir(3.0, 4.0); + Handle(AdaptorVec_AIS) anAisDir = new AdaptorVec_AIS(gp_Pnt2d(0.0, 0.0), aDir, 1.0, 0.3); + anAisDir->SetText(" gp_Dir2d"); + myObject2d.Append(anAisDir); + myResult << "gp_Dir2d coordinates: X: " << aDir.X() << ", Y: " << aDir.Y() << std::endl; + + // Defines a non-persistent vector in 2D space. + gp_Vec2d aVec(aDir); + aVec = aVec * 2; + Handle(AdaptorVec_AIS) anAisVec = new AdaptorVec_AIS(gp_Pnt2d(0.0, 5.0), aVec, 0.3); + anAisVec->SetText(" gp_Vec2d"); + myObject2d.Append(anAisVec); + myResult << "gp_Vec2d magnitude: " << aVec.Magnitude() << std::endl; +} + +void GeometrySamples::InfinityLines2dSample() +{ + // Describes an axis in the plane (2D space) + gp_Ax2d anAx2d(gp_Pnt2d(0.0, 0.0), gp_Dir2d(1.0, 0.0)); + Handle(AdaptorVec_AIS) anAisAx2d = new AdaptorVec_AIS(anAx2d.Location(), anAx2d.Direction(), 1.0, 0.3); + anAisAx2d->SetText(" gp_Ax2d"); + myObject2d.Append(anAisAx2d); + + // Describes a coordinate system in a plane (2D space). + gp_Ax22d anAx22d(gp_Pnt2d(0.0, 2.0), gp_Dir2d(1.0, 1.0), Standard_False); + Handle(AdaptorVec_AIS) anAisAx2d_X = new AdaptorVec_AIS(anAx22d.Location(), anAx22d.XDirection(), 1.0, 0.3); + anAisAx2d_X->SetText(" gp_Ax2d X"); + myObject2d.Append(anAisAx2d_X); + Handle(AdaptorVec_AIS) anAisAx2d_Y = new AdaptorVec_AIS(anAx22d.Location(), anAx22d.YDirection(), 1.0, 0.3); + anAisAx2d_Y->SetText(" gp_Ax2d Y"); + myObject2d.Append(anAisAx2d_Y); + + // Describes a line in 2D space. A line is positioned in the plane with an axis (a gp_Ax2d object) which gives + // the line its origin and unit vector. A line and an axis are similar objects, thus, + // we can convert one into the other. A line provides direct access to the majority of the edit and query + // functions available on its positioning axis. + gp_Lin2d aLin2d(gp_Pnt2d(2.0, 4.0), gp_Dir2d(0.0, -1.0)); + Handle(AdaptorVec_AIS) anAisLin = new AdaptorVec_AIS(aLin2d.Location(), aLin2d.Direction(), 1.0, 0.3); + anAisLin->SetText(" gp_Lin2d"); + myObject2d.Append(anAisLin); +} + +void GeometrySamples::SecondOrderCurves2dSample() +{ + // Describes a circle in the plane (2D space). A circle is defined by its radius + // and positioned in the plane with a coordinate system (a gp_Ax22d object) + gp_Circ2d aCirc2d; + aCirc2d.SetLocation(gp_Pnt2d(0.0, 0.0)); + aCirc2d.SetRadius(10.0); + Handle(Geom2d_Circle) aGeomCircle = new Geom2d_Circle(aCirc2d); + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeomCircle, Aspect_TOL_SOLID); + myObject2d.Append(anAisCirc); + + // Describes an ellipse in the plane (2D space). An ellipse is defined by its major + // and minor radii and positioned in the plane with a coordinate system (a gp_Ax22d object) + gp_Elips2d anElips(gp_Ax2d(gp_Pnt2d(0.0, 30.0), gp_Dir2d(1.0, 0.0)), 20.0, 10.0); + Handle(Geom2d_Ellipse) aGeomEllipse = new Geom2d_Ellipse(anElips); + Handle(AdaptorCurve2d_AIS) anAisEllipse = new AdaptorCurve2d_AIS(aGeomEllipse, Aspect_TOL_DASH); + myObject2d.Append(anAisEllipse); + + // Describes a parabola in the plane (2D space). A parabola is defined by its focal length + // (that is, the distance between its focus and apex) and positioned in the plane with + // a coordinate system (a gp_Ax22d object) + gp_Parab2d aParab2d(gp_Ax2d(gp_Pnt2d(20.0, 0.0), gp_Dir2d(1.0, 0.0)), 10.0); + Handle(Geom2d_Parabola) aGeomParabola = new Geom2d_Parabola(aParab2d); + Handle(Geom2d_TrimmedCurve) aTrimmedParabola = new Geom2d_TrimmedCurve(aGeomParabola, 40.0, -40.0); + Handle(AdaptorCurve2d_AIS) anAisParabola = new AdaptorCurve2d_AIS(aTrimmedParabola, Aspect_TOL_DOT); + myObject2d.Append(anAisParabola); + + // Describes a branch of a hyperbola in the plane (2D space). A hyperbola is defined by its major and + // minor radii, and positioned in the plane with a coordinate system (a gp_Ax22d object) + gp_Hypr2d aHypr2d(gp_Ax2d(gp_Pnt2d(20.0, 0.0), gp_Dir2d(1.0, 0.0)), 20.0, 10.0); + Handle(Geom2d_Hyperbola) aGeomHyperbola = new Geom2d_Hyperbola(aHypr2d); + Handle(Geom2d_TrimmedCurve) aTrimmedHyperbola = new Geom2d_TrimmedCurve(aGeomHyperbola, 2.0, -2.0); + Handle(AdaptorCurve2d_AIS) anAisHyperbola = new AdaptorCurve2d_AIS(aTrimmedHyperbola, Aspect_TOL_DOTDASH); + myObject2d.Append(anAisHyperbola); +} + +void GeometrySamples::BarycenterPoint3dSample() +{ + // Barycenter of 2 points + gp_Pnt aPnt1(11, 2, 3); + gp_Pnt aPnt2(13, 4, 5); + gp_Pnt aBarycenterPnt2 = aPnt1; + Standard_Real anAlpha = 3; + Standard_Real anBeta = 7; + // Assigns the result of the following expression to this point: + // (Alpha*this + Beta*P) / (Alpha + Beta) + aBarycenterPnt2.BaryCenter(anAlpha, aPnt2, anBeta); + DisplayPnt(aPnt1, "Pnt1", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt2, "Pnt2", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aBarycenterPnt2, "Barycenter Pnt", Aspect_TOM_O_PLUS, 0.5); + + // BaryCenter of an array of point + gp_Pnt aP1(0, 0, 5); + gp_Pnt aP2(1, 2, 3); + gp_Pnt aP3(2, 3, -2); + gp_Pnt aP4(4, 3, 5); + gp_Pnt aP5(5, 5, 4); + TColgp_Array1OfPnt aPntArray(1, 5); + aPntArray.SetValue(1, aP1); + aPntArray.SetValue(2, aP2); + aPntArray.SetValue(3, aP3); + aPntArray.SetValue(4, aP4); + aPntArray.SetValue(5, aP5); + + Standard_Real Tolerance = 8; + GProp_PEquation aPEquation(aPntArray, Tolerance); + + gp_Pnt aBarycenterPnt5; // P declaration + bool isPoint = false; + if (aPEquation.IsPoint()) + { + isPoint = true; + aBarycenterPnt5 = aPEquation.Point(); + myResult << "GProp_PEquation is a point" << std::endl; + } + else + { + isPoint = false; + myResult << "GProp_PEquation is not a point" << std::endl; + } + + if (aPEquation.IsLinear()) + { + /*... */ + } + if (aPEquation.IsPlanar()) + { + /*... */ + } + if (aPEquation.IsSpace()) + { + /*... */ + } + + const TCollection_AsciiString aPointName("P"); + for (Standard_Integer i = aPntArray.Lower(); i <= aPntArray.Upper(); i++) + { + TCollection_AsciiString aString(i); + aString = aPointName + aString; + DisplayPnt(aPntArray(i), aString, Aspect_TOM_STAR, 0.5); + } + + DisplayPnt(aBarycenterPnt5, "Barycenter of 5 points", Aspect_TOM_O_STAR, 0.5); + myResult << " IsPoint = "; + if (isPoint) + { + myResult << "True --> " << " P ( " << aBarycenterPnt5.X() << aBarycenterPnt5.Y() << aBarycenterPnt5.Z() << " );" << std::endl; + } + else + { + myResult << "False"; + } + myResult << std::endl << " IsLinear = " << (aPEquation.IsLinear() ? "True" : "False"); + myResult << std::endl << " IsPlanar = " << (aPEquation.IsPlanar() ? "True" : "False"); + myResult << std::endl << " IsSpace = " << (aPEquation.IsSpace() ? "True" : "False"); +} + +void GeometrySamples::RotatedVector3dSample() +{ + gp_Vec aBaseVec(0.0, 0.0, 10.0); + gp_Pnt aZeroPnt(0.0, 0.0, 0.0); + gp_Vec aRotatedVec = aBaseVec.Rotated(gp_Ax1(aZeroPnt, gp_Dir(1.0, 0.0, 0.0)), M_PI_4); + + Handle(AdaptorVec_AIS) aBaseVecAIS = new AdaptorVec_AIS(aZeroPnt, aBaseVec); + aBaseVecAIS->SetText(" Base vector"); + myObject3d.Append(aBaseVecAIS); + Handle(AdaptorVec_AIS) aRotatedVecAIS = new AdaptorVec_AIS(aZeroPnt, aRotatedVec); + aRotatedVecAIS->SetText(" Rotated vector"); + myObject3d.Append(aRotatedVecAIS); + Standard_Real anAdgle = aBaseVec.Angle(aRotatedVec)*180.0 / M_PI; + myResult << "An angle between vectors = " << anAdgle << std::endl; +} + +void GeometrySamples::MirroredLine3dSample() +{ + gp_Lin aBaseLin(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(1.0, 1.0, 1.0)); + gp_Ax2 aXyzAxis; + gp_Lin aMirroredLin = aBaseLin.Mirrored(aXyzAxis); + + Handle(AdaptorVec_AIS) aBaseLineAis = new AdaptorVec_AIS(aBaseLin.Location(), aBaseLin.Direction(), 8.0); + aBaseLineAis->SetText(" Base Line"); + myObject3d.Append(aBaseLineAis); + Handle(AdaptorVec_AIS) aMirroredLineAis = new AdaptorVec_AIS(aMirroredLin.Location(), aMirroredLin.Direction(), 8.0); + aMirroredLineAis->SetText(" Mirrored Line"); + myObject3d.Append(aMirroredLineAis); + Handle(AIS_Plane) anAisPlane = new AIS_Plane (new Geom_Plane(gp_Ax3(aXyzAxis)), aXyzAxis.Location(), + gp_Pnt(10.0, 10.0, 0.0), gp_Pnt(-10.0, -10.0, 0.0), Standard_False); + myObject3d.Append(anAisPlane); + Standard_Real anAdgle = aBaseLin.Angle(aMirroredLin)*180.0 / M_PI; + myResult << "An angle between lines = " << anAdgle << std::endl; +} + +void GeometrySamples::ScaledEllipse3dSample() +{ + gp_Ax2 anAxis2(gp_Pnt(), gp_Dir(0.0, 0.0, 1.0)); + gp_Elips anBaseElips(anAxis2, 20.0, 10.0); + gp_Elips anScaledElips = anBaseElips.Scaled(gp_Pnt(), 2.5); + + Handle(Geom_Ellipse) aBaseGeomEllipse = new Geom_Ellipse(anBaseElips); + Handle(AdaptorCurve_AIS) anAisBaseEllipce = new AdaptorCurve_AIS(aBaseGeomEllipse); + myObject3d.Append(anAisBaseEllipce); + + Handle(Geom_Ellipse) aScaledGeomEllipse = new Geom_Ellipse(anScaledElips); + Handle(AdaptorCurve_AIS) anAisScaledEllipce = new AdaptorCurve_AIS(aScaledGeomEllipse); + myObject3d.Append(anAisScaledEllipce); +} + +void GeometrySamples::TransformedCylinder3dSample() +{ + gp_Cylinder aBaseCylinder(gp_Ax3(), 10.0); + gp_Trsf aRotTrsf; + aRotTrsf.SetRotation(gp_Ax1(gp_Pnt(), gp_Dir(1.0, 0.0, 0.0)), M_PI_2); + gp_Trsf aScaleTrsf; + aScaleTrsf.SetScale(gp_Pnt(), 1.5); + gp_Trsf aTranslTrsf; + aTranslTrsf.SetTranslation(gp_Vec(30.0, 0.0, 0.0)); + gp_Trsf aComplexTrsf = aRotTrsf * aScaleTrsf * aTranslTrsf; + gp_Cylinder aTransfCylinder = aBaseCylinder.Transformed(aComplexTrsf); + + Handle(Geom_CylindricalSurface) aBaseCylinderSurface = new Geom_CylindricalSurface(aBaseCylinder); + Handle(AIS_Shape) anAisBaseCylinder = new AIS_Shape(BRepBuilderAPI_MakeFace( + aBaseCylinderSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisBaseCylinder); + Handle(Geom_CylindricalSurface) aTransfCylinderSurface = new Geom_CylindricalSurface(aTransfCylinder); + Handle(AIS_Shape) anAisTransfCylinder = new AIS_Shape(BRepBuilderAPI_MakeFace( + aTransfCylinderSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisTransfCylinder); +} + +void GeometrySamples::TranslatedTorus3dSample() +{ + gp_Torus aBaseTorus(gp_Ax3(gp_Pnt(), gp_Dir(0.0, 0.0, 1.0)), 40.0, 10.0); + gp_Torus aTranslatedTorus = aBaseTorus.Translated(gp_Vec(70.0, 70.0, 70.0)); + + Handle(Geom_ToroidalSurface) aBaseSurface = new Geom_ToroidalSurface(aBaseTorus); + Handle(AIS_Shape) anAisBaseShape = new AIS_Shape(BRepBuilderAPI_MakeFace( + aBaseSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisBaseShape); + Handle(Geom_ToroidalSurface) aTranslSurface = new Geom_ToroidalSurface(aTranslatedTorus); + Handle(AIS_Shape) anAisTranslShape = new AIS_Shape(BRepBuilderAPI_MakeFace( + aTranslSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisTranslShape); +} + +void GeometrySamples::ConjugateObjects3dSample() +{ + gp_Hypr aHypr(gp_Ax2(), 20.0, 10.0); + gp_Ax1 anAsymptote1 = aHypr.Asymptote1(); + gp_Ax1 anAsymptote2 = aHypr.Asymptote2(); + gp_Ax1 aDirectrix1 = aHypr.Directrix1(); + gp_Ax1 aDirectrix2 = aHypr.Directrix2(); + gp_Pnt aFocus1 = aHypr.Focus1(); + gp_Pnt aFocus2 = aHypr.Focus2(); + gp_Pnt aLocation = aHypr.Location(); + + Handle(AdaptorVec_AIS) anAsy1AIS = new AdaptorVec_AIS(anAsymptote1.Location(), gp_Vec(anAsymptote1.Direction())*10.0); + anAsy1AIS->SetText(" Asymptote 1"); + myObject3d.Append(anAsy1AIS); + Handle(AdaptorVec_AIS) anAsy2AIS = new AdaptorVec_AIS(anAsymptote2.Location(), gp_Vec(anAsymptote2.Direction())*10.0); + anAsy2AIS->SetText(" Asymptote 2"); + myObject3d.Append(anAsy2AIS); + Handle(AdaptorVec_AIS) anDir1AIS = new AdaptorVec_AIS(aDirectrix1.Location(), gp_Vec(aDirectrix1.Direction())*10.0); + anDir1AIS->SetText(" Directrix 1"); + myObject3d.Append(anDir1AIS); + Handle(AdaptorVec_AIS) anDir2AIS = new AdaptorVec_AIS(aDirectrix2.Location(), gp_Vec(aDirectrix2.Direction())*10.0); + anDir2AIS->SetText(" Directrix 2"); + myObject3d.Append(anDir2AIS); + + DisplayPnt(aFocus1, "Focus 1", Aspect_TOM_PLUS, 2.0); + DisplayPnt(aFocus2, "Focus 2", Aspect_TOM_PLUS, 2.0); + DisplayPnt(aLocation, "Location", Aspect_TOM_O_STAR, 2.0); + + Handle(Geom_Hyperbola) aGeomHyperbola = new Geom_Hyperbola(aHypr); + Handle(Geom_TrimmedCurve) aTrimmedHyperbola = new Geom_TrimmedCurve(aGeomHyperbola, 2.0, -2.0); + Handle(AdaptorCurve_AIS) anAisHyperbola = new AdaptorCurve_AIS(aTrimmedHyperbola); + myObject3d.Append(anAisHyperbola); +} + +void GeometrySamples::ProjectionOfPoint3dSample() +{ + gp_Sphere aSphere(gp_Ax3(), 10.0); + gp_Pnt aBasePnt(20.0, 20.0, 20.0); + // A projection point in surface coordinate + gp_Pnt2d aPrjPnt2d = ProjLib::Project(aSphere, aBasePnt); + gp_Pnt aPrjPnt = ElSLib::Value(aPrjPnt2d.X(), aPrjPnt2d.Y(), aSphere); + + DisplayPnt(aBasePnt, "Base point", Aspect_TOM_PLUS, 2.0); + DisplayPnt(aPrjPnt, "Projection point", Aspect_TOM_O_STAR, 2.0); + Handle(Geom_SphericalSurface) aSphericalSurface = new Geom_SphericalSurface(aSphere); + Handle(AIS_Shape) anAisSphere = new AIS_Shape(BRepBuilderAPI_MakeFace( + aSphericalSurface, 0.0, 2.0*M_PI, 0.0, 2.0*M_PI, Precision::Confusion()).Shape()); + myObject3d.Append(anAisSphere); +} + +void GeometrySamples::MinimalDistance3dSample() +{ + gp_Cylinder aCylinder(gp_Ax3(gp_Pnt(), gp_Dir(0.0, 0.0, 1.0)), 10.0); + gp_Lin aLine(gp_Pnt(20.0, 0.0, 5.0), gp_Dir(0.0, 1.0, 0.0)); + Extrema_ExtElCS anExtrema_ExtElCS(aLine, aCylinder); + + if (anExtrema_ExtElCS.IsDone()) + { + NCollection_Array1<gp_Vec> aVecArray(1, anExtrema_ExtElCS.NbExt()); + NCollection_Array1<gp_Pnt> aPntArray(1, anExtrema_ExtElCS.NbExt()); + for (Standard_Integer i = 1; i <= anExtrema_ExtElCS.NbExt(); i++) + { + Extrema_POnCurv aCurvPoint; + Extrema_POnSurf aSurfPoint; + anExtrema_ExtElCS.Points(i, aCurvPoint, aSurfPoint); + gp_Pnt aCurvPnt = aCurvPoint.Value(); + gp_Pnt aSurfPnt = aSurfPoint.Value(); + + DisplayPnt(aCurvPnt, TCollection_AsciiString(i), Aspect_TOM_O_PLUS, 2.0); + DisplayPnt(aSurfPnt, TCollection_AsciiString(i), Aspect_TOM_O_STAR, 2.0); + gp_Vec aVec(aCurvPnt, aSurfPnt); + aVecArray.SetValue(i, aVec); + aPntArray.SetValue(i, aCurvPnt); + } + Standard_Integer aMinDistIndex(0); + Standard_Real aMinDistance = std::numeric_limits<Standard_Real>::max(); + for (Standard_Integer i = 1; i <= anExtrema_ExtElCS.NbExt(); i++) + { + if (aMinDistance > aVecArray(i).Magnitude()) + { + aMinDistIndex = i; + aMinDistance = aVecArray(i).Magnitude(); + } + } + Handle(AdaptorVec_AIS) anMinDistanceAis = + new AdaptorVec_AIS(aPntArray(aMinDistIndex), aVecArray(aMinDistIndex)); + anMinDistanceAis->SetText(" Min distance"); + myObject3d.Append(anMinDistanceAis); + } + Handle(Geom_CylindricalSurface) aCylindricalSurface = new Geom_CylindricalSurface(aCylinder); + Handle(AIS_Shape) anAisCylinder = new AIS_Shape(BRepBuilderAPI_MakeFace( + aCylindricalSurface, 0.0, 2.0*M_PI, 0.0, 10.0, Precision::Confusion()).Shape()); + myObject3d.Append(anAisCylinder); + Handle(AdaptorVec_AIS) anLineAis = new AdaptorVec_AIS(aLine.Location(), aLine.Direction(), 8.0); + anLineAis->SetText(" gp_Lin"); + myObject3d.Append(anLineAis); +} + +void GeometrySamples::Intersection3dSample() +{ + gp_Lin aLine(gp_Pnt(0.0, 0.0, 10.0), gp_Dir(0.0, 1.0, 0.0)); + gp_Cone aCone(gp_Ax3(gp_Pnt(), gp_Dir(0.0, 0.0, 1.0)), 0.25*M_PI, 0.0); + IntAna_Quadric anIntAna_Quadric(aCone); + IntAna_IntConicQuad anIntAna_IntConicQuad(aLine, anIntAna_Quadric); + if (anIntAna_IntConicQuad.IsDone()) + { + for (int i = 1; i <= anIntAna_IntConicQuad.NbPoints(); i++) + { + const gp_Pnt& aIntersectionPnt = anIntAna_IntConicQuad.Point(i); + DisplayPnt(aIntersectionPnt, TCollection_AsciiString(i)); + } + } + Handle(AdaptorVec_AIS) aLineVecAIS = new AdaptorVec_AIS(aLine.Location(), gp_Vec(aLine.Direction())*5.0); + aLineVecAIS->SetText(" Base vector"); + myObject3d.Append(aLineVecAIS); + Handle(Geom_ConicalSurface) aConicalSurface = new Geom_ConicalSurface(aCone); + Handle(AIS_Shape) anAisCone = new AIS_Shape(BRepBuilderAPI_MakeFace( + aConicalSurface, 0.0, 2.0*M_PI, 0.0, 20.0, Precision::Confusion()).Shape()); + myObject3d.Append(anAisCone); +} + +void GeometrySamples::TranslatedPoint2dSample() +{ + gp_Pnt2d aPnt1; + gp_Pnt2d aPnt2 = aPnt1.Translated(gp_Vec2d(10.0, 10.0)); + DisplayPnt(aPnt1, "1", Aspect_TOM_PLUS, 1.0); + DisplayPnt(aPnt2, "2", Aspect_TOM_PLUS, 1.0); + gp_Vec2d aTranslationVec(aPnt1, aPnt2); + Handle(AdaptorVec_AIS) aVecAIS = new AdaptorVec_AIS(aPnt1, aTranslationVec); + aVecAIS->SetText(" Translation"); + myObject2d.Append(aVecAIS); +} + +void GeometrySamples::RotatedDirection2dSample() +{ + gp_Dir2d aBaseDir(1.0, 1.0); + gp_Dir2d aRotatedDir = aBaseDir.Rotated(M_PI_4); + + myResult << "An angle between directions: " << aBaseDir.Angle(aRotatedDir)*180.0 / M_PI << " grad"; + Handle(AdaptorVec_AIS) aBaseAIS = new AdaptorVec_AIS(gp_Pnt2d(), aBaseDir, 5.0); + aBaseAIS->SetText(" Base"); + myObject2d.Append(aBaseAIS); + Handle(AdaptorVec_AIS) aRotatedAIS = new AdaptorVec_AIS(gp_Pnt2d(), aRotatedDir, 5.0); + aRotatedAIS->SetText(" Rotated"); + myObject2d.Append(aRotatedAIS); +} + +void GeometrySamples::MirroredAxis2dSample() +{ + gp_Ax22d aBaseAx(gp_Pnt2d(10.0, 0.0), gp_Dir2d(1.0, 0.0), Standard_True); + gp_Ax22d aMirrorAx = aBaseAx.Mirrored(gp_Pnt2d()); + + DisplayPnt(gp_Pnt2d(), "Mirror point", Aspect_TOM_PLUS, 1.0); + Handle(AdaptorVec_AIS) aBaseX_AIS = new AdaptorVec_AIS(aBaseAx.Location(), aBaseAx.XDirection(), 5.0); + aBaseX_AIS->SetText(" X (Base)"); + myObject2d.Append(aBaseX_AIS); + Handle(AdaptorVec_AIS) aBaseY_AIS = new AdaptorVec_AIS(aBaseAx.Location(), aBaseAx.YDirection(), 5.0); + aBaseY_AIS->SetText("Y (Base)"); + myObject2d.Append(aBaseY_AIS); + Handle(AdaptorVec_AIS) aMirrorX_AIS = new AdaptorVec_AIS(aMirrorAx.Location(), aMirrorAx.XDirection(), 5.0); + aMirrorX_AIS->SetText("X (Mirror)"); + myObject2d.Append(aMirrorX_AIS); + Handle(AdaptorVec_AIS) aMirrorY_AIS = new AdaptorVec_AIS(aMirrorAx.Location(), aMirrorAx.YDirection(), 5.0); + aMirrorY_AIS->SetText(" Y (Mirror)"); + myObject2d.Append(aMirrorY_AIS); +} + +void GeometrySamples::TransformedEllipse2dSample() +{ + // Creates an ellipse with the major axis, the major and the minor radius. + // The location of the MajorAxis is the center of the ellipse.The sense of + // parametrization is given by Sense.Warnings : It is possible to create + // an ellipse with MajorRadius = MinorRadius.Raises + // ConstructionError if MajorRadius < MinorRadius or MinorRadius < 0.0. + gp_Elips2d aBaseEllips(gp_Ax2d(gp_Pnt2d(), gp_Dir2d(1.0, 0.0)), 20.0, 10.0); + gp_Trsf2d aRotTrsf; + aRotTrsf.SetRotation(gp_Pnt2d(), M_PI_4); + gp_Trsf2d aScaleTrsf; + aScaleTrsf.SetScale(gp_Pnt2d(), 1.5); + gp_Trsf2d aTranslTrsf; + aTranslTrsf.SetTranslation(gp_Vec2d(30.0, 0.0)); + gp_Trsf2d aComplexTrsf = aRotTrsf * aScaleTrsf * aTranslTrsf; + gp_Elips2d aTransfEllips = aBaseEllips.Transformed(aComplexTrsf); + + Handle(Geom2d_Ellipse) aBaseEllipse = new Geom2d_Ellipse(aBaseEllips); + Handle(AdaptorCurve2d_AIS) anAisBaseEllipse = new AdaptorCurve2d_AIS(aBaseEllipse, Aspect_TOL_DASH); + myObject2d.Append(anAisBaseEllipse); + Handle(Geom2d_Ellipse) aTransfEllipse = new Geom2d_Ellipse(aTransfEllips); + Handle(AdaptorCurve2d_AIS) anAisTransfEllipse = new AdaptorCurve2d_AIS(aTransfEllipse, Aspect_TOL_DASH); + myObject2d.Append(anAisTransfEllipse); +} + +void GeometrySamples::ConjugateObjects2dSample() +{ + gp_Parab2d aParab(gp_Ax2d(), 20.0); + gp_Ax2d aDirectrix = aParab.Directrix(); + gp_Pnt2d aFocus = aParab.Focus(); + gp_Pnt2d aLocation = aParab.Location(); + gp_Ax2d aMirror = aParab.MirrorAxis(); + + Handle(AdaptorVec_AIS) aDirectAIS = new AdaptorVec_AIS(aDirectrix.Location(), gp_Vec2d(aDirectrix.Direction())*10.0); + aDirectAIS->SetText(" Directrix"); + myObject2d.Append(aDirectAIS); + Handle(AdaptorVec_AIS) aMirrorAIS = new AdaptorVec_AIS(aMirror.Location(), gp_Vec2d(aMirror.Direction())*10.0); + aMirrorAIS->SetText(" Mirror Axis"); + myObject2d.Append(aMirrorAIS); + + DisplayPnt(aFocus, "Focus", Aspect_TOM_PLUS, -3.0); + DisplayPnt(aLocation, " Location", Aspect_TOM_O_STAR, 3.0); + Handle(Geom2d_Parabola) aGeomParabola = new Geom2d_Parabola(aParab); + Handle(Geom2d_TrimmedCurve) aTrimmedParabola = new Geom2d_TrimmedCurve(aGeomParabola, 40.0, -40.0); + Handle(AdaptorCurve2d_AIS) anAisParabola = new AdaptorCurve2d_AIS(aTrimmedParabola, Aspect_TOL_DOT); + myObject2d.Append(anAisParabola); +} + +void GeometrySamples::Tangent2dSample() +{ + gp_Circ2d aCirc1(gp_Ax2d(gp_Pnt2d(0.0, 0.0), gp_Vec2d(1.0, 0.0)), 10.0); + gp_Circ2d aCirc2 = aCirc1.Translated(gp_Vec2d(50.0, 0.0)); + aCirc2.SetRadius(20.0); + + GccEnt_QualifiedCirc aQaCirc1(aCirc1, GccEnt_outside); + GccEnt_QualifiedCirc aQaCirc2(aCirc2, GccEnt_outside); + + GccAna_Lin2d2Tan aLin2d2Tan(aQaCirc1, aQaCirc2, 1E-6); + if (aLin2d2Tan.IsDone()) + { + for (int i = 1; i <= aLin2d2Tan.NbSolutions(); i++) + { + const gp_Lin2d& aTangentLin = aLin2d2Tan.ThisSolution(i); + Handle(AdaptorVec_AIS) anAisLin = new AdaptorVec_AIS(aTangentLin.Location(), aTangentLin.Direction(), 20.0); + myObject2d.Append(anAisLin); + } + } + + Handle(Geom2d_Circle) aCircle1 = new Geom2d_Circle(aCirc1); + Handle(AdaptorCurve2d_AIS) anAisCirc1 = new AdaptorCurve2d_AIS(aCircle1, Aspect_TOL_SOLID); + myObject2d.Append(anAisCirc1); + Handle(Geom2d_Circle) aCircle2 = new Geom2d_Circle(aCirc2); + Handle(AdaptorCurve2d_AIS) anAisCirc2 = new AdaptorCurve2d_AIS(aCircle2, Aspect_TOL_SOLID); + myObject2d.Append(anAisCirc2); +} + +void GeometrySamples::ProjectionOfPoint2dSample() +{ + gp_Pnt2d aPntToProject(40.0, 40.0); + gp_Circ2d aCirc(gp_Ax2d(), 20.0); + Handle(Geom2d_Circle) aGeom_Circle = new Geom2d_Circle(aCirc); + Geom2dAPI_ProjectPointOnCurve aProjector(aPntToProject, aGeom_Circle); + gp_Pnt2d aProjectionPnt = aProjector.NearestPoint(); + + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeom_Circle, Aspect_TOL_SOLID); + myObject2d.Append(anAisCirc); + DisplayPnt(aPntToProject, "Pnt to project"); + DisplayPnt(aProjectionPnt, "Projection Pnt", Aspect_TOM_O_STAR); +} + +void GeometrySamples::MinimalDistance2dSample() +{ + gp_Lin2d aLin(gp_Pnt2d(-40.0, 0.0), gp_Dir2d(1.0, 1.0)); + Handle(Geom2d_Line) aGeom_Line = new Geom2d_Line(aLin); + gp_Circ2d aCirc(gp_Ax2d(), 20.0); + Handle(Geom2d_Circle) aGeom_Circle = new Geom2d_Circle(aCirc); + + Geom2dAPI_ExtremaCurveCurve anExtremaFinder(aGeom_Line, aGeom_Circle, + std::numeric_limits<Standard_Real>::min(), + std::numeric_limits<Standard_Real>::max(), 0.0, M_PI*2.0); + if (anExtremaFinder.NbExtrema()) + { + gp_Pnt2d aPnt1, aPnt2; + anExtremaFinder.NearestPoints(aPnt1, aPnt2); + myResult << "Extrema found: " << anExtremaFinder.NbExtrema() << std::endl; + myResult << "Minimal distance: " << anExtremaFinder.LowerDistance() << std::endl; + DisplayPnt(aPnt1, "1"); + DisplayPnt(aPnt2, "2"); + } + else + { + myResult << "No Extrema found" << std::endl; + } + + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeom_Circle, Aspect_TOL_SOLID); + myObject2d.Append(anAisCirc); + Handle(AdaptorVec_AIS) anAisLin = new AdaptorVec_AIS(aLin.Location(), aLin.Direction(), 60.0); + anAisLin->SetText(" gp_Lin2d"); + myObject2d.Append(anAisLin); +} + +void GeometrySamples::Intersection2dSample() +{ + gp_Lin2d aLin(gp_Pnt2d(-20.0, 20.0), gp_Dir2d(1.0, -1.5)); + Handle(Geom2d_Line) aGeom_Line = new Geom2d_Line(aLin); + gp_Parab2d aParab(gp_Ax2d(), 20.0); + Handle(Geom2d_Parabola) aGeom_Parabola = new Geom2d_Parabola(aParab); + + Geom2dAPI_InterCurveCurve anIntersectFinder(aGeom_Line, aGeom_Parabola); + for (Standard_Integer i = 1; i <= anIntersectFinder.NbPoints(); i++) + { + gp_Pnt2d aPnt = anIntersectFinder.Point(i); + DisplayPnt(aPnt, i); + } + + myResult << "Number of intersections : " << anIntersectFinder.NbPoints() << std::endl; + + Handle(Geom2d_Parabola) aGeomParabola = new Geom2d_Parabola(aParab); + Handle(Geom2d_TrimmedCurve) aTrimmedParabola = new Geom2d_TrimmedCurve(aGeomParabola, 60.0, -60.0); + Handle(AdaptorCurve2d_AIS) anAisParabola = new AdaptorCurve2d_AIS(aTrimmedParabola, Aspect_TOL_DOT); + myObject2d.Append(anAisParabola); + Handle(AdaptorVec_AIS) anAisLin = new AdaptorVec_AIS(aLin.Location(), aLin.Direction(), 90.0); + anAisLin->SetText(" gp_Lin2d"); + myObject2d.Append(anAisLin); +} + +void GeometrySamples::PointInfo3dSample() +{ + gp_Pnt aPnt1; + gp_Pnt aPnt2(10.0, 10.0, 10.0); + gp_Pnt aPnt3(10.0, -10.0, 0.0); + gp_Pnt aPnt4(10.0, 10.0, 10.0); + Standard_Boolean anIsEqual2_3 = aPnt2.IsEqual(aPnt3, 1E-6); + Standard_Boolean anIsEqual2_4 = aPnt2.IsEqual(aPnt4, 1E-6); + Standard_Real aDistance1_2 = aPnt1.Distance(aPnt2); + Standard_Real aDistance2_4 = aPnt2.Distance(aPnt4); + Standard_Real aSquareDistance1_2 = aPnt1.SquareDistance(aPnt2); + Standard_Real aSquareDistance2_4 = aPnt2.SquareDistance(aPnt4); + + myResult << "A coordinate of a point 1: X: " << aPnt1.X() << " Y: " << aPnt1.Y() << " Z: " << aPnt1.Z() << std::endl; + myResult << "A coordinate of a point 2: X: " << aPnt2.X() << " Y: " << aPnt2.Y() << " Z: " << aPnt2.Z() << std::endl; + myResult << "A coordinate of a point 3: X: " << aPnt3.X() << " Y: " << aPnt3.Y() << " Z: " << aPnt3.Z() << std::endl; + myResult << "A coordinate of a point 4: X: " << aPnt4.X() << " Y: " << aPnt4.Y() << " Z: " << aPnt4.Z() << std::endl; + + if (anIsEqual2_3) + { + myResult << "A point 2 is equal to a point 3" << std::endl; + } + else + { + myResult << "A point 2 is different from a point 3" << std::endl; + } + if (anIsEqual2_4) + { + myResult << "A point 2 is equal to a point 4" << std::endl; + } + else + { + myResult << "A point 2 is different from a point 4" << std::endl; + } + myResult << "A distance from a point 1 to a point 2 is: " << aDistance1_2 << std::endl; + myResult << "A distance from a point 2 to a point 4 is: " << aDistance2_4 << std::endl; + + myResult << "A square distance from a point 1 to a point 2 is: " << aSquareDistance1_2 << std::endl; + myResult << "A square distance from a point 2 to a point 4 is: " << aSquareDistance2_4 << std::endl; + + DisplayPnt(aPnt1, "1", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt2, "2 & 4", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt3, "3", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt4, "", Aspect_TOM_PLUS, 0.5); +} + +void GeometrySamples::EllipseInfo3dSample() +{ + gp_Elips anElips(gp_Ax2(gp_Pnt(), gp_Dir(1.0, 0.0, 0.0)), 20.0, 10.0); + Standard_Real anArea = anElips.Area(); + // Returns the eccentricity of the ellipse between 0.0 and 1.0 + // If f is the distance between the center of the ellipse and the Focus1 then + // the eccentricity e = f / MajorRadius. Returns 0 if MajorRadius = 0. + Standard_Real anEccentricity = anElips.Eccentricity(); + // Returns the distance between the center of the ellipse and focus1 or focus2. + Standard_Real aFocal = anElips.Focal(); + // Returns p = (1 - e * e) * MajorRadius where e is the eccentricity + // of the ellipse. Returns 0 if MajorRadius = 0. + Standard_Real aParameter = anElips.Parameter(); + + myResult << "Ellipse area = " << anArea << " square units" << std::endl; + myResult << "Eccentricity = " << anEccentricity; + myResult << "Focal distance = " << aFocal; + myResult << "Ellipse parameter = " << aParameter; + + gp_Pnt aCenter = anElips.Location(); + gp_Pnt aFocus1 = anElips.Focus1(); + gp_Pnt aFocus2 = anElips.Focus2(); + DisplayPnt(aCenter, "Center", Aspect_TOM_PLUS, 2.0); + DisplayPnt(aFocus1, "focus 1", Aspect_TOM_PLUS, 2.0); + DisplayPnt(aFocus2, "focus 2", Aspect_TOM_PLUS, 2.0); + + Handle(Geom_Ellipse) aGeomEllipse = new Geom_Ellipse(anElips); + Handle(AdaptorCurve_AIS) anAisEllipce = new AdaptorCurve_AIS(aGeomEllipse); + myObject3d.Append(anAisEllipce); +} + +void GeometrySamples::PointInfo2dSample() +{ + gp_Pnt2d aPnt1; + gp_Pnt2d aPnt2(10.0, 10.0); + gp_Pnt2d aPnt3(10.0, -10.0); + gp_Pnt2d aPnt4(10.0, 10.0); + Standard_Boolean anIsEqual2_3 = aPnt2.IsEqual(aPnt3, 1E-6); + Standard_Boolean anIsEqual2_4 = aPnt2.IsEqual(aPnt4, 1E-6); + Standard_Real aDistance1_2 = aPnt1.Distance(aPnt2); + Standard_Real aDistance2_4 = aPnt2.Distance(aPnt4); + Standard_Real aSquareDistance1_2 = aPnt1.SquareDistance(aPnt2); + Standard_Real aSquareDistance2_4 = aPnt2.SquareDistance(aPnt4); + + myResult << "A coordinate of a point 1: X: " << aPnt1.X() << " Y: " << aPnt1.Y() << std::endl; + myResult << "A coordinate of a point 2: X: " << aPnt2.X() << " Y: " << aPnt2.Y() << std::endl; + myResult << "A coordinate of a point 3: X: " << aPnt3.X() << " Y: " << aPnt3.Y() << std::endl; + myResult << "A coordinate of a point 4: X: " << aPnt4.X() << " Y: " << aPnt4.Y() << std::endl; + if (anIsEqual2_3) + { + myResult << "A point 2 is equal to a point 3" << std::endl; + } + else + { + myResult << "A point 2 is different from a point 3" << std::endl; + } + if (anIsEqual2_4) + { + myResult << "A point 2 is equal to a point 4" << std::endl; + } + else + { + myResult << "A point 2 is different from a point 4" << std::endl; + } + + myResult << "A distance from a point 1 to a point 2 is: " << aDistance1_2 << std::endl; + myResult << "A distance from a point 2 to a point 4 is: " << aDistance2_4 << std::endl; + + myResult << "A square distance from a point 1 to a point 2 is: " << aSquareDistance1_2 << std::endl; + myResult << "A square distance from a point 2 to a point 4 is: " << aSquareDistance2_4 << std::endl; + + DisplayPnt(aPnt1, "1", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt2, "2 & 4", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt3, "3", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt4, ""); +} + +void GeometrySamples::CircleInfo2dSample() +{ + gp_Circ2d aCirc(gp_Ax22d(gp_Pnt2d(10.0, 10.0), gp_Vec2d(1.0, 0.0)), 10.0); + gp_Pnt2d aPnt1(0.0, 10.0); + gp_Pnt2d aPnt2(10.0, 0.0); + gp_Pnt2d aPnt3(20.0, 20.0); + + if (aCirc.Contains(aPnt1, 1E-6)) + { + DisplayPnt(aPnt1, "1", Aspect_TOM_STAR, 3.0); + myResult << "A circle contains a point 1" << std::endl; + } + else + { + DisplayPnt(aPnt1, "1", Aspect_TOM_PLUS, 1.0); + myResult << "A circle does contain a point 1" << std::endl; + } + if (aCirc.Contains(aPnt2, 1E-6)) + { + DisplayPnt(aPnt2, "2", Aspect_TOM_STAR, 1.0); + myResult << "A circle contains a point 2" << std::endl; + } + else + { + DisplayPnt(aPnt2, "2", Aspect_TOM_PLUS, 1.0); + myResult << "A circle does contain a point 2" << std::endl; + } + if (aCirc.Contains(aPnt3, 1E-6)) + { + DisplayPnt(aPnt3, "3", Aspect_TOM_STAR, 1.0); + myResult << "A circle contains a point 3" << std::endl; + } + else + { + DisplayPnt(aPnt3, "3", Aspect_TOM_PLUS, 1.0); + myResult << "A circle does contain a point 3" << std::endl; + } + myResult << "Circle area = " << aCirc.Area() << "square units" << std::endl; + Handle(Geom2d_Circle) aGeomCircle = new Geom2d_Circle(aCirc); + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeomCircle); + myObject2d.Append(anAisCirc); +} + +void GeometrySamples::FreeStyleCurves3dSample() +{ + // Define points. + gp_Pnt aPnt1(0.0, 0.0, 0.0); + gp_Pnt aPnt2(5.0, 5.0, 0.0); + gp_Pnt aPnt3(10.0, 5.0, 0.0); + gp_Pnt aPnt4(15.0, 0.0, 0.0); + + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoles(1, 4); + aPoles.SetValue(1, aPnt1); + aPoles.SetValue(2, aPnt2); + aPoles.SetValue(3, aPnt3); + aPoles.SetValue(4, aPnt4); + + // Define BSpline weights. + TColStd_Array1OfReal aBSplineWeights(1, 4); + aBSplineWeights.SetValue(1, 1.0); + aBSplineWeights.SetValue(2, 0.5); + aBSplineWeights.SetValue(3, 0.5); + aBSplineWeights.SetValue(4, 1.0); + + // Define knots. + TColStd_Array1OfReal aKnots(1, 2); + aKnots.SetValue(1, 0.0); + aKnots.SetValue(2, 1.0); + + // Define multiplicities. + TColStd_Array1OfInteger aMults(1, 2); + aMults.SetValue(1, 4); + aMults.SetValue(2, 4); + + // Define BSpline degree and periodicity. + Standard_Integer aDegree = 3; + Standard_Boolean aPeriodic = Standard_False; + + // Create a BSpline curve. + Handle(Geom_BSplineCurve) aBSplineCurve = new Geom_BSplineCurve( + aPoles, aBSplineWeights, aKnots, aMults, aDegree, aPeriodic); + myResult << "Geom_BSplineCurve was created in red" << std::endl; + + // Define Bezier weights. + TColStd_Array1OfReal aBezierWeights(1, 4); + aBezierWeights.SetValue(1, 0.5); + aBezierWeights.SetValue(2, 1.5); + aBezierWeights.SetValue(3, 1.5); + aBezierWeights.SetValue(4, 0.5); + + // Create Bezier curve. + Handle(Geom_BezierCurve) aBezierCurve = new Geom_BezierCurve(aPoles, aBezierWeights); + myResult << "Geom_BezierCurve was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisBSplineCurve = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aBSplineCurve).Shape()); + Handle(AIS_ColoredShape) anAisBezierCurve = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aBezierCurve).Shape()); + anAisBSplineCurve->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisBezierCurve->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisBSplineCurve); + myObject3d.Append(anAisBezierCurve); + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(aPnt1))); + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(aPnt2))); + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(aPnt3))); + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(aPnt4))); +} + +void GeometrySamples::AnalyticalSurfaces3dSample() +{ + // Define a XY plane. + gp_Pln aPln(gp::Origin(), gp::DZ()); + // Create plane geometry. + Handle(Geom_Plane) aPlaneSurf = new Geom_Plane(aPln); + myResult << "Geom_Plane was created in red" << std::endl; + + // Define a cylinder. + gp_Cylinder aCyl(gp::XOY(), 2.5); + // Create cylindrical surface. + Handle(Geom_CylindricalSurface) aCylSurf = new Geom_CylindricalSurface(aCyl); + myResult << "Geom_CylindricalSurface was created in green" << std::endl; + + // Define a cone. + gp_Cone aCone(gp::XOY(), M_PI_4, 2.5); + // Create conical surface. + Handle(Geom_ConicalSurface) aConeSurf = new Geom_ConicalSurface(aCone); + myResult << "Geom_ConicalSurface was created in blue" << std::endl; + + // Define a sphere. + gp_Pnt aSphereCenter(15.0, 15.0, 15.0); + gp_Sphere aSphere(gp_Ax3(aSphereCenter, gp::DZ()), 8.0); + // Create conical surface. + Handle(Geom_SphericalSurface) aSphereSurf = new Geom_SphericalSurface(aSphere); + myResult << "Geom_SphericalSurface was created in cyan" << std::endl; + + // Define a sphere. + gp_Pnt aTorusCenter(-15.0, -15.0, 25.0); + gp_Torus aTorus(gp_Ax3(aTorusCenter, gp::DZ()), 15.0, 5.0); + // Create toroidal surface. + Handle(Geom_ToroidalSurface) aTorusSurf = new Geom_ToroidalSurface(aTorus); + myResult << "Geom_ToroidalSurface was created in yellow" << std::endl; + + Handle(AIS_ColoredShape) anAisPlane = new AIS_ColoredShape(BRepBuilderAPI_MakeFace( + aPlaneSurf, 0.0, 20.0, 0.0, 20.0, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisCylinder = new AIS_ColoredShape(BRepBuilderAPI_MakeFace( + aCylSurf, 0.0, 2.0 * M_PI, 5.0, 15.0, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisCone = new AIS_ColoredShape(BRepBuilderAPI_MakeFace( + aConeSurf, 0.0, 2.0 * M_PI, 0.0, 15.0, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisSphere = new AIS_ColoredShape(BRepBuilderAPI_MakeFace( + aSphereSurf, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisTorus = new AIS_ColoredShape(BRepBuilderAPI_MakeFace( + aTorusSurf, Precision::Confusion()).Shape()); + anAisPlane->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisCylinder->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisCone->SetColor(Quantity_Color(Quantity_NOC_BLUE1)); + anAisSphere->SetColor(Quantity_Color(Quantity_NOC_CYAN1)); + anAisTorus->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisPlane); + myObject3d.Append(anAisCylinder); + myObject3d.Append(anAisCone); + myObject3d.Append(anAisSphere); + myObject3d.Append(anAisTorus); +} + +void GeometrySamples::FreeStyleSurfaces3dSample() +{ + // Define a 4x4 grid of points for BSpline surface. + TColgp_Array2OfPnt aBSplinePnts(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + gp_Pnt aPnt; + aPnt.SetX(5.0 * i); + for (Standard_Integer j = 1; j <= 4; ++j) + { + aPnt.SetY(5.0 * j); + if (1 < i && i < 4 && 1 < j && j < 4) + { + aPnt.SetZ(5.0); + } + else + { + aPnt.SetZ(0.0); + } + aBSplinePnts.SetValue(i, j, aPnt); + } + } + + // Define a 4x4 grid of points for Bezier surface. + TColgp_Array2OfPnt aBezierPnts(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + gp_Pnt aPnt; + aPnt.SetX(20.0 + 5.0 * i); + for (Standard_Integer j = 1; j <= 4; ++j) + { + aPnt.SetY(20.0 + 5.0 * j); + if (1 < i && i < 4 && 1 < j && j < 4) + { + aPnt.SetZ(5.0); + } + else + { + aPnt.SetZ(0.0); + } + aBezierPnts.SetValue(i, j, aPnt); + } + } + + // Define BSpline weights. + TColStd_Array2OfReal aBSplineWeights(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + for (Standard_Integer j = 1; j <= 4; ++j) + { + if (1 < i && i < 4 && 1 < j && j < 4) + { + aBSplineWeights.SetValue(i, j, 0.5); + } + else + { + aBSplineWeights.SetValue(i, j, 1.0); + } + } + } + + // Define knots. + TColStd_Array1OfReal aUKnots(1, 2), aVKnots(1, 2); + aUKnots.SetValue(1, 0.0); + aUKnots.SetValue(2, 1.0); + aVKnots.SetValue(1, 0.0); + aVKnots.SetValue(2, 1.0); + + // Define multiplicities. + TColStd_Array1OfInteger aUMults(1, 2), aVMults(1, 2); + aUMults.SetValue(1, 4); + aUMults.SetValue(2, 4); + aVMults.SetValue(1, 4); + aVMults.SetValue(2, 4); + + // Define BSpline degree and periodicity. + Standard_Integer aUDegree = 3; + Standard_Integer aVDegree = 3; + Standard_Boolean aUPeriodic = Standard_False; + Standard_Boolean aVPeriodic = Standard_False; + + // Create a BSpline surface. + Handle(Geom_BSplineSurface) aBSplineSurf = new Geom_BSplineSurface( + aBSplinePnts, aBSplineWeights, aUKnots, aVKnots, + aUMults, aVMults, aUDegree, aVDegree, aUPeriodic, aVPeriodic); + myResult << "Geom_BSplineSurface was created in red" << std::endl; + + // Define BSpline weights. + TColStd_Array2OfReal aBezierWeights(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + for (Standard_Integer j = 1; j <= 4; ++j) + { + if (1 < i && i < 4 && 1 < j && j < 4) + { + aBezierWeights.SetValue(i, j, 1.5); + } + else + { + aBezierWeights.SetValue(i, j, 0.5); + } + } + } + + // Create a Bezier surface. + Handle(Geom_BezierSurface) aBezierSurf = new Geom_BezierSurface(aBezierPnts, aBezierWeights); + myResult << "Geom_BezierSurface was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisBSplineSurf = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aBSplineSurf, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisBezierSurf = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aBezierSurf, Precision::Confusion()).Shape()); + anAisBSplineSurf->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisBezierSurf->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisBSplineSurf); + myObject3d.Append(anAisBezierSurf); + for (TColgp_Array2OfPnt::Iterator anIt(aBSplinePnts); anIt.More(); anIt.Next()) + { + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(anIt.Value()))); + } + for (TColgp_Array2OfPnt::Iterator anIt(aBezierPnts); anIt.More(); anIt.Next()) + { + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(anIt.Value()))); + } +} + +void GeometrySamples::FreeStyleCurves2dSample() +{ + + // Define points. + gp_Pnt2d aPnt1(0.0, 0.0); + gp_Pnt2d aPnt2(5.0, 5.0); + gp_Pnt2d aPnt3(10.0, 5.0); + gp_Pnt2d aPnt4(15.0, 0.0); + + // Add points to the curve poles array. + TColgp_Array1OfPnt2d aBSplinePoles(1, 4); + aBSplinePoles.SetValue(1, aPnt1); + aBSplinePoles.SetValue(2, aPnt2); + aBSplinePoles.SetValue(3, aPnt3); + aBSplinePoles.SetValue(4, aPnt4); + + // Define BSpline weights. + TColStd_Array1OfReal aBSplineWeights(1, 4); + aBSplineWeights.SetValue(1, 1.0); + aBSplineWeights.SetValue(2, 0.5); + aBSplineWeights.SetValue(3, 0.5); + aBSplineWeights.SetValue(4, 1.0); + + // Define knots. + TColStd_Array1OfReal aKnots(1, 2); + aKnots.SetValue(1, 0.0); + aKnots.SetValue(2, 1.0); + + // Define multiplicities. + TColStd_Array1OfInteger aMults(1, 2); + aMults.SetValue(1, 4); + aMults.SetValue(2, 4); + + // Define BSpline degree and periodicity. + Standard_Integer aDegree = 3; + Standard_Boolean aPeriodic = Standard_False; + + // Create a BSpline curve. + Handle(Geom2d_BSplineCurve) aBSplineCurve = + new Geom2d_BSplineCurve(aBSplinePoles, aBSplineWeights, aKnots, aMults, aDegree, aPeriodic); + + + TColgp_Array1OfPnt2d aBezierPoles(1, 4); + gp_Vec2d anUp10Vec(0.0, 10.0); + aBezierPoles.SetValue(1, aPnt1.Translated(anUp10Vec)); + aBezierPoles.SetValue(2, aPnt2.Translated(anUp10Vec)); + aBezierPoles.SetValue(3, aPnt3.Translated(anUp10Vec)); + aBezierPoles.SetValue(4, aPnt4.Translated(anUp10Vec)); + + // Define Bezier weights. + TColStd_Array1OfReal aBezierWeights(1, 4); + aBezierWeights.SetValue(1, 0.5); + aBezierWeights.SetValue(2, 1.5); + aBezierWeights.SetValue(3, 1.5); + aBezierWeights.SetValue(4, 0.5); + + // Create Bezier curve. + Handle(Geom2d_BezierCurve) aBezierCurve = new Geom2d_BezierCurve(aBezierPoles, aBezierWeights); + + Handle(AdaptorCurve2d_AIS) anAisBSpline = new AdaptorCurve2d_AIS(aBSplineCurve); + myObject2d.Append(anAisBSpline); + Handle(AdaptorCurve2d_AIS) anAisBezier = new AdaptorCurve2d_AIS(aBezierCurve); + myObject2d.Append(anAisBezier); + + DisplayPnt(aPnt1, "1", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt2, "2", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt3, "3", Aspect_TOM_PLUS, 0.5); + DisplayPnt(aPnt4, "4", Aspect_TOM_PLUS, 0.5); +} + +void GeometrySamples::TrimmedCurve3dSample() +{ + // Define a circle placed in the origin of XY coordinate + // plane and with the radius equal to 5. + gp_Circ aCirc(gp::XOY(), 5.0); + // Create a closed circular curve. + Handle(Geom_Circle) aCircCurve = new Geom_Circle(aCirc); + myResult << "Geom_Circle was created in yellow" << std::endl; + + // Cut off a quarter of the circle. + Handle(Geom_TrimmedCurve) aCircQuater = new Geom_TrimmedCurve(aCircCurve, 0.0, M_PI_2); + myResult << "Geom_TrimmedCurve was created in red" << std::endl; + + Handle(AIS_ColoredShape) anAisCirc = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aCircCurve).Shape()); + Handle(AIS_ColoredShape) anAisCircQuater = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aCircQuater).Shape()); + anAisCirc->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisCircQuater->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisCircQuater->SetWidth(2.5); + myObject3d.Append(anAisCirc); + myObject3d.Append(anAisCircQuater); +} + +void GeometrySamples::OffsetCurve3dSample() +{ + // Define a circle placed in the origin of XY coordinate + // plane and with the radius equal to 5. + gp_Circ aCirc(gp::XOY(), 5.0); + // Create a closed circular curve. + Handle(Geom_Circle) aCircCurve = new Geom_Circle(aCirc); + myResult << "Geom_Circle was created in yellow" << std::endl; + + // An offset curve is a curve at constant distance (Offset) from + // a basis curve in a reference direction V. + // The offset curve takes its parametrization from the basis curve. + // The Offset curve is in the direction of the normal N + // defined with the cross product T^V, where the vector T + // is given by the first derivative on the basis curve with non zero length. + // The distance offset may be positive or negative to indicate the + // preferred side of the curve: + // . distance offset >0 => the curve is in the direction of N + // . distance offset <0 => the curve is in the direction of - N + // On the Offset curve: + // Value (U) = BasisCurve.Value(U) + (Offset * (T ^ V)) / ||T ^ V|| + // At any point the Offset direction V must not be parallel to the + // vector T and the vector T must not have null length else the + // offset curve is not defined. + + // Expand the circle by Offset equal to a quarter of the radius + // with direction V equal to Z. + Standard_Real anExpandOffset = +aCirc.Radius() / 4.0; + gp_Dir anExpandDir = gp::DZ(); + Handle(Geom_OffsetCurve) anExpandCircCurve = new Geom_OffsetCurve( + aCircCurve, anExpandOffset, anExpandDir); + myResult << "Geom_OffsetCurve (expanded circle) was created in red" << std::endl; + + // Collapse the circle by Offset equal to a half of the radius with direction V equal to Z. + Standard_Real anCollapseOffset = -aCirc.Radius() / 2.0; + gp_Dir anCollapseDir = gp::DZ(); + Handle(Geom_OffsetCurve) anCollapseCircCurve = new Geom_OffsetCurve (aCircCurve, anCollapseOffset, anCollapseDir); + myResult << "Geom_OffsetCurve (collapsed circle) was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisCirc = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aCircCurve).Shape()); + Handle(AIS_ColoredShape) anAisExpandCirc = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(anExpandCircCurve).Shape()); + Handle(AIS_ColoredShape) anAisCpllapsedCirc = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(anCollapseCircCurve).Shape()); + anAisCirc->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisExpandCirc->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisCpllapsedCirc->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisCirc); + myObject3d.Append(anAisExpandCirc); + myObject3d.Append(anAisCpllapsedCirc); +} + +void GeometrySamples::BSplineFromCircle3dSample() +{ + // Define a circle placed in the origin of XY coordinate + // plane and with the radius equal to 5. + gp_Circ aCirc(gp::XOY(), 5.0); + // Create a closed circular curve. + Handle(Geom_Circle) aCircCurve = new Geom_Circle(aCirc); + myResult << "Geom_Circle was created in yellow" << std::endl; + + // Convert the circle curve to a BSpline one. + Handle(Geom_BSplineCurve) aBSplineFromCirc = GeomConvert::CurveToBSplineCurve(aCircCurve); + myResult << "Geom_BSplineCurve was created in red:" << std::endl; + myResult << "Degree: " << aBSplineFromCirc->Degree() << std::endl; + myResult << "Periodic: " << (aBSplineFromCirc->IsPeriodic() ? "Yes" : "No") << std::endl; + myResult << "Poles: [" << aBSplineFromCirc->Poles().Size() << "]" << std::endl; + for (TColgp_Array1OfPnt::Iterator anIt(aBSplineFromCirc->Poles()); anIt.More(); anIt.Next()) + { + myResult << " (" << anIt.Value().X() << ", " << anIt.Value().Y() << ", " << anIt.Value().Z() << ")" << std::endl; + } + + Handle(AIS_ColoredShape) anAisCirc = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aCircCurve).Shape()); + Handle(AIS_ColoredShape) anAisBSpline = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aBSplineFromCirc).Shape()); + anAisCirc->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisBSpline->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisCirc); + myObject3d.Append(anAisBSpline); +} + +void GeometrySamples::TrimmedSurface3dSample() +{ + // Define a XY plane. + gp_Pln aPln(gp::XOY()); + // Create a plane surface. + Handle(Geom_Plane) aPlaneSurf = new Geom_Plane(aPln); + myResult << "Geom_Plane was created" << std::endl; + + // Trim [0 ... 30 X 0 ... 50] rectangular range. + Standard_Real aUMin = 0.0; + Standard_Real aUMax = 30.0; + Standard_Real aVMin = 0.0; + Standard_Real aVMax = 50.0; + Handle(Geom_RectangularTrimmedSurface) aTrimmedPlaneSurf + = new Geom_RectangularTrimmedSurface(aPlaneSurf, aUMin, aUMax, aVMin, aVMax); + myResult << "Geom_RectangularTrimmedSurface was created in red" << std::endl; + + Handle(AIS_Plane) anAisPlane = new AIS_Plane(aPlaneSurf); + Handle(AIS_ColoredShape) anAisTimmedPlane = new AIS_ColoredShape (BRepBuilderAPI_MakeFace (aTrimmedPlaneSurf, 0.001).Shape()); + anAisTimmedPlane->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisPlane); + myObject3d.Append(anAisTimmedPlane); +} + +void GeometrySamples::OffsetSurface3dSample() +{ + // Define a XY plane. + gp_Pln aPln(gp::XOY()); + // Create a plane surface. + Handle(Geom_Plane) aPlaneSurf = new Geom_Plane(aPln); + myResult << "Geom_Plane was created" << std::endl; + + // An offset surface is defined by: + // - the basis surface to which it is parallel, and + // - the distance between the offset surface and its basis surface. + // A point on the offset surface is built by measuring the + // offset value along the normal vector at a point on the + // basis surface. This normal vector is given by the cross + // product D1u^D1v, where D1u and D1v are the + // vectors tangential to the basis surface in the u and v + // parametric directions at this point. The side of the + // basis surface on which the offset is measured + // depends on the sign of the offset value. + + // Offset the plane in the normal direction. + Standard_Real aPosOffset = 10.0; + Handle(Geom_OffsetSurface) aPosOffsetSurf = new Geom_OffsetSurface(aPlaneSurf, aPosOffset); + myResult << "Geom_OffsetSurface with " << aPosOffset << " was created in red" << std::endl; + + // Offset the plane in direction opposite to the normal one. + Standard_Real aNegOffset = -15.0; + Handle(Geom_OffsetSurface) aNegOffsetSurf = new Geom_OffsetSurface(aPlaneSurf, aNegOffset); + myResult << "Geom_OffsetSurface with " << aNegOffset << " was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisPlane = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aPlaneSurf, 0.0, 10.0, 0.0, 10.0, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisPosOffsetPlane = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aPosOffsetSurf, 0.0, 10.0, 0.0, 10.0, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisNegOffsetPlane = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aNegOffsetSurf, 0.0, 10.0, 0.0, 10.0, Precision::Confusion()).Shape()); + anAisPosOffsetPlane->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisNegOffsetPlane->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisPlane); + myObject3d.Append(anAisPosOffsetPlane); + myObject3d.Append(anAisNegOffsetPlane); +} + +void GeometrySamples::ExtrusionSurface3dSample() +{ + // Create an ellipse curve in XY plane. + Standard_Real aMinorRadius = 10.0; + Standard_Real aMajorRadius = 20.0; + Handle(Geom_Ellipse) anEllipseCurve = new Geom_Ellipse(gp::XOY(), aMajorRadius, aMinorRadius); + myResult << "Geom_Ellipse was created in yellow" << std::endl; + + // Make a linear extrusion of the ellipse at 45 degrees to Z axis + gp_Dir aDirOfExtr = gp::DZ(); + Handle(Geom_SurfaceOfLinearExtrusion) aLinExtrSurf + = new Geom_SurfaceOfLinearExtrusion(anEllipseCurve, aDirOfExtr); + myResult << "Geom_SurfaceOfLinearExtrusion was created in red" << std::endl; + + Handle(AIS_ColoredShape) anAisEllipse = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(anEllipseCurve).Shape()); + Handle(AIS_ColoredShape) anAisExtrSurf = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aLinExtrSurf, 0.0, 2.0 * M_PI, 0.0, 30.0, + Precision::Confusion()).Shape()); + anAisEllipse->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEllipse->SetWidth(2.5); + anAisExtrSurf->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisEllipse); + myObject3d.Append(anAisExtrSurf); +} + +void GeometrySamples::RevolutionSurface3dSample() +{ + // Create an ellipse curve in XY plane with + // the center at (-10, 0, 0). + Standard_Real aMinorRadius = 5.0; + Standard_Real aMajorRadius = 10.0; + gp_Pnt aCenter(-30.0, 0.0, 0.0); + Handle(Geom_Ellipse) anEllipseCurve = new Geom_Ellipse(gp_Ax2(aCenter, gp::DZ()), + aMajorRadius, aMinorRadius); + myResult << "Geom_Ellipse was created in yellow" << std::endl; + + // Make a revolution of the ellipse around Y axis + Handle(Geom_SurfaceOfRevolution) aRevolSurf = new Geom_SurfaceOfRevolution(anEllipseCurve, gp::OY()); + myResult << "Geom_SurfaceOfRevolution was created in red" << std::endl; + + Handle(AIS_ColoredShape) anAisEllipse = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(anEllipseCurve).Shape()); + Handle(AIS_ColoredShape) anAisRevolSurf = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aRevolSurf, Precision::Confusion()).Shape()); + anAisEllipse->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEllipse->SetWidth(2.5); + anAisRevolSurf->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisEllipse); + myObject3d.Append(anAisRevolSurf); +} + +void GeometrySamples::TrimmedCurve2dSample() +{ + // Create a closed circular curve. + Handle(Geom2d_Circle) aGeomCircle = new Geom2d_Circle(gp_Ax2d(gp_Pnt2d(), gp_Vec2d(1.0, 0.0)), 5.0); + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeomCircle); + myObject2d.Append(anAisCirc); + + // Cut off a quarter of the circle. + Handle(Geom2d_TrimmedCurve) aCircQuater = new Geom2d_TrimmedCurve(aGeomCircle, 0.0, M_PI_2); + aCircQuater->Translate(gp_Vec2d(15.0, 0.0)); + Handle(AdaptorCurve2d_AIS) anAisCircQuater = new AdaptorCurve2d_AIS(aCircQuater); + myObject2d.Append(anAisCircQuater); +} + +void GeometrySamples::OffsetCurve2dSample() +{ + Handle(Geom2d_Circle) aGeomCircle = new Geom2d_Circle(gp_Ax2d(gp_Pnt2d(), gp_Vec2d(1.0, 0.0)), 5.0); + + Standard_Real anExpandOffset = aGeomCircle->Radius() / 4.0; + Handle(Geom2d_OffsetCurve) anExpandCircCurve = new Geom2d_OffsetCurve(aGeomCircle, anExpandOffset); + + Standard_Real anCollapseOffset = -aGeomCircle->Radius() / 2.0; + Handle(Geom2d_OffsetCurve) anCollapseCircCurve = new Geom2d_OffsetCurve(aGeomCircle, anCollapseOffset); + + Handle(AdaptorCurve2d_AIS) anAisCirc = new AdaptorCurve2d_AIS(aGeomCircle); + myObject2d.Append(anAisCirc); + Handle(AdaptorCurve2d_AIS) anAisExpand = new AdaptorCurve2d_AIS(anExpandCircCurve); + myObject2d.Append(anAisExpand); + Handle(AdaptorCurve2d_AIS) anAisCollapse = new AdaptorCurve2d_AIS(anCollapseCircCurve); + myObject2d.Append(anAisCollapse); +} + +void GeometrySamples::BoundingBoxOfSurface3dSample() +{ + // Define a 4x4 grid of points for BSpline surface. + TColgp_Array2OfPnt aPoints(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + gp_Pnt aPnt; + aPnt.SetX(5.0 * i); + for (Standard_Integer j = 1; j <= 4; ++j) + { + aPnt.SetY(5.0 * j); + if (1 < i && i < 4 && 1 < j && j < 4) + { + aPnt.SetZ(5.0); + } + else + { + aPnt.SetZ(0.0); + } + aPoints.SetValue(i, j, aPnt); + } + } + + // Make a BSpline surface from the points array. + Handle(Geom_BSplineSurface) aBSplineSurf = GeomAPI_PointsToBSplineSurface(aPoints).Surface(); + myResult << "Geom_BSplineSurface was created" << std::endl; + + // Compute BSpline surface bounding box. + Bnd_Box aBndBox; + BndLib_AddSurface::AddOptimal(GeomAdaptor_Surface(aBSplineSurf), Precision::Confusion(), aBndBox); + myResult << "Bounding box:" << std::endl; + myResult << " Min corner = [ " + << aBndBox.CornerMin().X() << ", " + << aBndBox.CornerMin().Y() << ", " + << aBndBox.CornerMin().Z() << " ]" << std::endl; + myResult << " Max corner = [ " + << aBndBox.CornerMax().X() << ", " + << aBndBox.CornerMax().Y() << ", " + << aBndBox.CornerMax().Z() << " ]" << std::endl; + + Handle(AIS_ColoredShape) anAisBSplineSurf = new AIS_ColoredShape( + BRepBuilderAPI_MakeFace(aBSplineSurf, Precision::Confusion()).Shape()); + Handle(AIS_ColoredShape) anAisBndBox = new AIS_ColoredShape( + BRepPrimAPI_MakeBox(aBndBox.CornerMin(), aBndBox.CornerMax()).Shell()); + myObject3d.Append(anAisBSplineSurf); + myObject3d.Append(anAisBndBox); + myContext->SetDisplayMode(anAisBndBox, 0, Standard_True); +} + +void GeometrySamples::BoundingBoxOfCurves3dSample() +{ + // Define points. + gp_Pnt aPnt1(0.0, 0.0, 10.0); + gp_Pnt aPnt2(5.0, 5.0, 5.0); + gp_Pnt aPnt3(10.0, 10.0, 15.0); + gp_Pnt aPnt4(15.0, 5.0, 20.0); + + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoles(1, 4); + aPoles.SetValue(1, aPnt1); + aPoles.SetValue(2, aPnt2); + aPoles.SetValue(3, aPnt3); + aPoles.SetValue(4, aPnt4); + + // Make a BSpline curve from the points array. + Handle(Geom_BSplineCurve) aBSplineCurve = GeomAPI_PointsToBSpline(aPoles).Curve(); + myResult << "aBSplineCurve was created" << std::endl; + + // Compute BSpline curve bounding box. + Bnd_Box aBndBox; + BndLib_Add3dCurve::AddOptimal(GeomAdaptor_Curve(aBSplineCurve), Precision::Confusion(), aBndBox); + myResult << "Bounding box:" << std::endl; + myResult << " Min corner = [ " + << aBndBox.CornerMin().X() << ", " + << aBndBox.CornerMin().Y() << ", " + << aBndBox.CornerMin().Z() << " ]" << std::endl; + myResult << " Max corner = [ " + << aBndBox.CornerMax().X() << ", " + << aBndBox.CornerMax().Y() << ", " + << aBndBox.CornerMax().Z() << " ]" << std::endl; + + Handle(AIS_ColoredShape) anAisBSplineCurve = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aBSplineCurve).Shape()); + Handle(AIS_ColoredShape) anAisBndBox = new AIS_ColoredShape (BRepPrimAPI_MakeBox(aBndBox.CornerMin(), aBndBox.CornerMax()).Shell()); + myObject3d.Append(anAisBSplineCurve); + myObject3d.Append(anAisBndBox); + myContext->SetDisplayMode(anAisBndBox, 0, Standard_True); +} + +void GeometrySamples::BoundingBoxOfCurves2dSample() +{ + // Define points. + gp_Pnt2d aPnt1(0.0, 0.0); + gp_Pnt2d aPnt2(5.0, 5.0); + gp_Pnt2d aPnt3(10.0, 10.0); + gp_Pnt2d aPnt4(15.0, 5.0); + + // Add points to the curve poles array. + TColgp_Array1OfPnt2d aPoles(1, 4); + aPoles.SetValue(1, aPnt1); + aPoles.SetValue(2, aPnt2); + aPoles.SetValue(3, aPnt3); + aPoles.SetValue(4, aPnt4); + + // Make a BSpline curve from the points array. + Handle(Geom2d_BSplineCurve) aBSplineCurve = Geom2dAPI_PointsToBSpline(aPoles).Curve(); + + // Compute BSpline curve bounding box. + Bnd_Box2d aBndBox; + BndLib_Add2dCurve::AddOptimal(aBSplineCurve, 0.0, 1.0, Precision::PConfusion(), aBndBox); + Standard_Real aXmin, aYmin, aXmax, aYmax; + aBndBox.Get(aXmin, aYmin, aXmax, aYmax); + + myResult << "Bounding box:" << std::endl; + myResult << " Min corner = [ " << aXmin << ", " << aYmin << " ]" << std::endl; + myResult << " Max corner = [ " << aXmax << ", " << aYmax << " ]" << std::endl; + + Handle(AdaptorCurve2d_AIS) anAisBSpline = new AdaptorCurve2d_AIS(aBSplineCurve); + + Handle(AdaptorVec_AIS) anAisVec1 = new AdaptorVec_AIS(gp_Pnt2d(aXmin, aYmin), gp_Pnt2d(aXmin, aYmax)); + Handle(AdaptorVec_AIS) anAisVec2 = new AdaptorVec_AIS(gp_Pnt2d(aXmin, aYmax), gp_Pnt2d(aXmax, aYmax)); + Handle(AdaptorVec_AIS) anAisVec3 = new AdaptorVec_AIS(gp_Pnt2d(aXmax, aYmax), gp_Pnt2d(aXmax, aYmin)); + Handle(AdaptorVec_AIS) anAisVec4 = new AdaptorVec_AIS(gp_Pnt2d(aXmax, aYmin), gp_Pnt2d(aXmin, aYmin)); + + myObject2d.Append(anAisBSpline); + myObject2d.Append(anAisVec1); + myObject2d.Append(anAisVec2); + myObject2d.Append(anAisVec3); + myObject2d.Append(anAisVec4); +} + +void GeometrySamples::DumpCircleInfoSample() +{ + // Define a circle placed in the origin of XY coordinate + // plane and with the radius equal to 0.5. + gp_Circ aCirc(gp::XOY(), 0.5); + // Create a closed circular curve. + Handle(Geom_Circle) aCircCurve = new Geom_Circle(aCirc); + myResult << "Geom_Circle was created:" << std::endl; + myResult << " Center = [ " + << aCircCurve->Position().Location().X() << ", " + << aCircCurve->Position().Location().Y() << ", " + << aCircCurve->Position().Location().Z() << " ]" + << std::endl; + myResult << " Radius = " << aCircCurve->Radius() << std::endl; + myResult << " Plane normal = [ " + << aCircCurve->Position().Direction().X() << ", " + << aCircCurve->Position().Direction().Y() << ", " + << aCircCurve->Position().Direction().Z() << " ]" + << std::endl; + + Handle(AIS_Circle) anAisCircle = new AIS_Circle(aCircCurve); + Handle(AIS_TextLabel) anAisCenterLabel = new AIS_TextLabel(); + anAisCenterLabel->SetText(" Center"); + anAisCenterLabel->SetPosition(aCircCurve->Position().Location()); + Handle(AIS_Point) anAisCenter = new AIS_Point(new Geom_CartesianPoint(aCirc.Location())); + Handle(AIS_Axis) anAisAxis = new AIS_Axis(new Geom_Axis2Placement(aCircCurve->Position()), AIS_TOAX_ZAxis); + myObject3d.Append(anAisCircle); + myObject3d.Append(anAisCenterLabel); + myObject3d.Append(anAisAxis); +} + +void GeometrySamples::DumpBSplineCurveInfoSample() +{ + // Define points. + gp_Pnt aPnt1(0.0, 0.0, 10.0); + gp_Pnt aPnt2(5.0, 5.0, 5.0); + gp_Pnt aPnt3(10.0, 10.0, 15.0); + gp_Pnt aPnt4(15.0, 5.0, 20.0); + + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoles(1, 4); + aPoles.SetValue(1, aPnt1); + aPoles.SetValue(2, aPnt2); + aPoles.SetValue(3, aPnt3); + aPoles.SetValue(4, aPnt4); + + // Make a BSpline curve from the points array + Handle(Geom_BSplineCurve) aBSplineCurve = GeomAPI_PointsToBSpline(aPoles).Curve(); + myResult << "aBSplineCurve was created:" << std::endl; + myResult << " Degree = " << aBSplineCurve->Degree() << std::endl; + myResult << " Parameter range = [ " + << aBSplineCurve->FirstParameter() << ", " + << aBSplineCurve->LastParameter() << " ]" + << std::endl; + NCollection_List<Standard_Real> aParams; + aParams.Append(0.75 * aBSplineCurve->FirstParameter() + 0.25 * aBSplineCurve->LastParameter()); + aParams.Append(0.50 * aBSplineCurve->FirstParameter() + 0.50 * aBSplineCurve->LastParameter()); + aParams.Append(0.25 * aBSplineCurve->FirstParameter() + 0.75 * aBSplineCurve->LastParameter()); + myResult << " Curve info:" << std::endl; + for (NCollection_List<Standard_Real>::Iterator anIt(aParams); anIt.More(); anIt.Next()) + { + Standard_Real aParam = anIt.Value(); + gp_Pnt aPnt; + gp_Vec aVec; + aBSplineCurve->D1(aParam, aPnt, aVec); + myResult << " Param = " << aParam << std::endl; + myResult << " P = [ " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << " ]" << std::endl; + myResult << " D = [ " << aVec.X() << ", " << aVec.Y() << ", " << aVec.Z() << " ]" << std::endl; + myObject3d.Append(new AIS_Point(new Geom_CartesianPoint(aPnt))); + Handle(AIS_TextLabel) anAisCenterLabel = new AIS_TextLabel(); + Standard_SStream aSS; + aSS << "P [" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << "]" << std::endl; + aSS << "D [" << aVec.X() << ", " << aVec.Y() << ", " << aVec.Z() << "]" << std::endl; + anAisCenterLabel->SetText(aSS.str().c_str()); + anAisCenterLabel->SetPosition(aPnt); + myObject3d.Append(anAisCenterLabel); + Handle(AIS_Axis) anAisD = new AIS_Axis(new Geom_Axis1Placement(gp_Ax1(aPnt, aVec))); + myObject3d.Append(anAisD); + } + + Handle(AIS_ColoredShape) anAisBSplineCurve = new AIS_ColoredShape (BRepBuilderAPI_MakeEdge(aBSplineCurve).Shape()); + anAisBSplineCurve->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBSplineCurve); +} diff --git a/samples/OCCTOverview/code/GeometrySamples.h b/samples/OCCTOverview/code/GeometrySamples.h new file mode 100644 index 0000000000..7da4ad7645 --- /dev/null +++ b/samples/OCCTOverview/code/GeometrySamples.h @@ -0,0 +1,102 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef GEOMETRYSAMPLES_H +#define GEOMETRYSAMPLES_H + +#include "BaseSample.h" + +//! Implements Geometry samples +class GeometrySamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(GeometrySamples, BaseSample) +public: + + GeometrySamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample(theSampleSourcePath, theContext) {} + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + void DisplayPnt (const gp_Pnt& thePnt, const TCollection_AsciiString& theText, + Aspect_TypeOfMarker theMarker = Aspect_TOM_PLUS, + Standard_Real theDistance = 5.0); + void DisplayPnt (const gp_Pnt2d& thePnt2d, const TCollection_AsciiString& theText, + Aspect_TypeOfMarker theMarker = Aspect_TOM_PLUS, + Standard_Real theDistance = 5.0); + + // One function for every sample + void ZeroDimensionObjects3dSample(); + void Vectors3dSample(); + void InfinityLines3dSample(); + void SecondOrderCurves3dSample(); + void PlaneSurfaces3dSample(); + void SecondOrderSurfaces3dSample(); + void ZeroDimensionObjects2dSample(); + void Vectors2dSample(); + void InfinityLines2dSample(); + void SecondOrderCurves2dSample(); + void BarycenterPoint3dSample(); + void RotatedVector3dSample(); + void MirroredLine3dSample(); + void ScaledEllipse3dSample(); + void TransformedCylinder3dSample(); + void TranslatedTorus3dSample(); + void ConjugateObjects3dSample(); + void ProjectionOfPoint3dSample(); + void MinimalDistance3dSample(); + void Intersection3dSample(); + void TranslatedPoint2dSample(); + void RotatedDirection2dSample(); + void MirroredAxis2dSample(); + void TransformedEllipse2dSample(); + void ConjugateObjects2dSample(); + void Tangent2dSample(); + void ProjectionOfPoint2dSample(); + void MinimalDistance2dSample(); + void Intersection2dSample(); + void PointInfo3dSample(); + void EllipseInfo3dSample(); + void PointInfo2dSample(); + void CircleInfo2dSample(); + void FreeStyleCurves3dSample(); + void AnalyticalSurfaces3dSample(); + void FreeStyleSurfaces3dSample(); + void FreeStyleCurves2dSample(); + void TrimmedCurve3dSample(); + void OffsetCurve3dSample(); + void BSplineFromCircle3dSample(); + void TrimmedSurface3dSample(); + void OffsetSurface3dSample(); + void ExtrusionSurface3dSample(); + void RevolutionSurface3dSample(); + void TrimmedCurve2dSample(); + void OffsetCurve2dSample(); + void BoundingBoxOfSurface3dSample(); + void BoundingBoxOfCurves3dSample(); + void BoundingBoxOfCurves2dSample(); + void DumpCircleInfoSample(); + void DumpBSplineCurveInfoSample(); +}; + +#endif //GEOMETRYSAMPLES_H diff --git a/samples/OCCTOverview/code/MakeBottle.cxx b/samples/OCCTOverview/code/MakeBottle.cxx new file mode 100644 index 0000000000..44307e0759 --- /dev/null +++ b/samples/OCCTOverview/code/MakeBottle.cxx @@ -0,0 +1,218 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "MakeBottle.h" + +#include <BRep_Tool.hxx> + +#include <BRepAlgoAPI_Fuse.hxx> + +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <BRepBuilderAPI_MakeFace.hxx> +#include <BRepBuilderAPI_MakeWire.hxx> +#include <BRepBuilderAPI_Transform.hxx> + +#include <BRepFilletAPI_MakeFillet.hxx> + +#include <BRepLib.hxx> + +#include <BRepOffsetAPI_MakeThickSolid.hxx> +#include <BRepOffsetAPI_ThruSections.hxx> + +#include <BRepPrimAPI_MakeCylinder.hxx> +#include <BRepPrimAPI_MakePrism.hxx> + +#include <GC_MakeArcOfCircle.hxx> +#include <GC_MakeSegment.hxx> + +#include <GCE2d_MakeSegment.hxx> + +#include <gp.hxx> +#include <gp_Ax1.hxx> +#include <gp_Ax2.hxx> +#include <gp_Ax2d.hxx> +#include <gp_Dir.hxx> +#include <gp_Dir2d.hxx> +#include <gp_Pnt.hxx> +#include <gp_Pnt2d.hxx> +#include <gp_Trsf.hxx> +#include <gp_Vec.hxx> + +#include <Geom_CylindricalSurface.hxx> +#include <Geom_Plane.hxx> +#include <Geom_Surface.hxx> +#include <Geom_TrimmedCurve.hxx> + +#include <Geom2d_Ellipse.hxx> +#include <Geom2d_TrimmedCurve.hxx> + +#include <TopExp_Explorer.hxx> + +#include <TopoDS.hxx> +#include <TopoDS_Edge.hxx> +#include <TopoDS_Face.hxx> +#include <TopoDS_Wire.hxx> +#include <TopoDS_Shape.hxx> +#include <TopoDS_Compound.hxx> + +#include <TopTools_ListOfShape.hxx> + +TopoDS_Shape MakeBottle (const Standard_Real theWidth, + const Standard_Real theHeight, + const Standard_Real theThickness) +{ + // Profile : Define Support Points + gp_Pnt aPnt1(-theWidth / 2., 0, 0); + gp_Pnt aPnt2(-theWidth / 2., -theThickness / 4., 0); + gp_Pnt aPnt3(0, -theThickness / 2., 0); + gp_Pnt aPnt4(theWidth / 2., -theThickness / 4., 0); + gp_Pnt aPnt5(theWidth / 2., 0, 0); + + // Profile : Define the Geometry + Handle(Geom_TrimmedCurve) anArcOfCircle = GC_MakeArcOfCircle(aPnt2, aPnt3, aPnt4); + Handle(Geom_TrimmedCurve) aSegment1 = GC_MakeSegment(aPnt1, aPnt2); + Handle(Geom_TrimmedCurve) aSegment2 = GC_MakeSegment(aPnt4, aPnt5); + + // Profile : Define the Topology + TopoDS_Edge anEdge1 = BRepBuilderAPI_MakeEdge(aSegment1); + TopoDS_Edge anEdge2 = BRepBuilderAPI_MakeEdge(anArcOfCircle); + TopoDS_Edge anEdge3 = BRepBuilderAPI_MakeEdge(aSegment2); + TopoDS_Wire aWire = BRepBuilderAPI_MakeWire(anEdge1, anEdge2, anEdge3); + + // Complete Profile + gp_Ax1 xAxis = gp::OX(); + gp_Trsf aTrsf; + + aTrsf.SetMirror(xAxis); + BRepBuilderAPI_Transform aBRepTrsf(aWire, aTrsf); + TopoDS_Shape aMirroredShape = aBRepTrsf.Shape(); + TopoDS_Wire aMirroredWire = TopoDS::Wire(aMirroredShape); + + BRepBuilderAPI_MakeWire mkWire; + mkWire.Add(aWire); + mkWire.Add(aMirroredWire); + TopoDS_Wire myWireProfile = mkWire.Wire(); + + // Body : Prism the Profile + TopoDS_Face myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile); + gp_Vec aPrismVec(0, 0, theHeight); + TopoDS_Shape myBody = BRepPrimAPI_MakePrism(myFaceProfile, aPrismVec); + + // Body : Apply Fillets + BRepFilletAPI_MakeFillet mkFillet(myBody); + TopExp_Explorer anEdgeExplorer(myBody, TopAbs_EDGE); + while (anEdgeExplorer.More()) + { + TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExplorer.Current()); + //Add edge to fillet algorithm + mkFillet.Add(theThickness / 12., anEdge); + anEdgeExplorer.Next(); + } + + myBody = mkFillet.Shape(); + + // Body : Add the Neck + gp_Pnt neckLocation(0, 0, theHeight); + gp_Dir neckAxis = gp::DZ(); + gp_Ax2 neckAx2(neckLocation, neckAxis); + + Standard_Real myNeckRadius = theThickness / 4.; + Standard_Real myNeckHeight = theHeight / 10.; + + BRepPrimAPI_MakeCylinder MKCylinder(neckAx2, myNeckRadius, myNeckHeight); + TopoDS_Shape myNeck = MKCylinder.Shape(); + + myBody = BRepAlgoAPI_Fuse(myBody, myNeck); + + // Body : Create a Hollowed Solid + TopoDS_Face faceToRemove; + Standard_Real zMax = -1; + + for (TopExp_Explorer aFaceExplorer(myBody, TopAbs_FACE); aFaceExplorer.More(); aFaceExplorer.Next()) + { + TopoDS_Face aFace = TopoDS::Face(aFaceExplorer.Current()); + // Check if <aFace> is the top face of the bottle�s neck + Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace); + if (aSurface->DynamicType() == STANDARD_TYPE(Geom_Plane)) + { + Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(aSurface); + gp_Pnt aPnt = aPlane->Location(); + Standard_Real aZ = aPnt.Z(); + if (aZ > zMax) + { + zMax = aZ; + faceToRemove = aFace; + } + } + } + + TopTools_ListOfShape facesToRemove; + facesToRemove.Append(faceToRemove); + BRepOffsetAPI_MakeThickSolid aSolidMaker; + aSolidMaker.MakeThickSolidByJoin(myBody, facesToRemove, -theThickness / 50, 1.e-3); + myBody = aSolidMaker.Shape(); + // Threading : Create Surfaces + Handle(Geom_CylindricalSurface) aCyl1 = new Geom_CylindricalSurface(neckAx2, myNeckRadius * 0.99); + Handle(Geom_CylindricalSurface) aCyl2 = new Geom_CylindricalSurface(neckAx2, myNeckRadius * 1.05); + + // Threading : Define 2D Curves + gp_Pnt2d aPnt(2. * M_PI, myNeckHeight / 2.); + gp_Dir2d aDir(2. * M_PI, myNeckHeight / 4.); + gp_Ax2d anAx2d(aPnt, aDir); + + Standard_Real aMajor = 2. * M_PI; + Standard_Real aMinor = myNeckHeight / 10; + + Handle(Geom2d_Ellipse) anEllipse1 = new Geom2d_Ellipse(anAx2d, aMajor, aMinor); + Handle(Geom2d_Ellipse) anEllipse2 = new Geom2d_Ellipse(anAx2d, aMajor, aMinor / 4); + Handle(Geom2d_TrimmedCurve) anArc1 = new Geom2d_TrimmedCurve(anEllipse1, 0, M_PI); + Handle(Geom2d_TrimmedCurve) anArc2 = new Geom2d_TrimmedCurve(anEllipse2, 0, M_PI); + gp_Pnt2d anEllipsePnt1 = anEllipse1->Value(0); + gp_Pnt2d anEllipsePnt2 = anEllipse1->Value(M_PI); + + Handle(Geom2d_TrimmedCurve) aSegment = GCE2d_MakeSegment(anEllipsePnt1, anEllipsePnt2); + // Threading : Build Edges and Wires + TopoDS_Edge anEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(anArc1, aCyl1); + TopoDS_Edge anEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment, aCyl1); + TopoDS_Edge anEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(anArc2, aCyl2); + TopoDS_Edge anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment, aCyl2); + TopoDS_Wire threadingWire1 = BRepBuilderAPI_MakeWire(anEdge1OnSurf1, anEdge2OnSurf1); + TopoDS_Wire threadingWire2 = BRepBuilderAPI_MakeWire(anEdge1OnSurf2, anEdge2OnSurf2); + BRepLib::BuildCurves3d(threadingWire1); + BRepLib::BuildCurves3d(threadingWire2); + + // Create Threading + BRepOffsetAPI_ThruSections aTool(Standard_True); + aTool.AddWire(threadingWire1); + aTool.AddWire(threadingWire2); + aTool.CheckCompatibility(Standard_False); + + TopoDS_Shape myThreading = aTool.Shape(); + + // Building the Resulting Compound + TopoDS_Compound aRes; + BRep_Builder aBuilder; + aBuilder.MakeCompound(aRes); + aBuilder.Add(aRes, myBody); + aBuilder.Add(aRes, myThreading); + + return aRes; +} diff --git a/samples/OCCTOverview/code/MakeBottle.h b/samples/OCCTOverview/code/MakeBottle.h new file mode 100644 index 0000000000..ad1e783064 --- /dev/null +++ b/samples/OCCTOverview/code/MakeBottle.h @@ -0,0 +1,33 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef MAKEBOTTLE_H +#define MAKEBOTTLE_H + +#include <Standard_Macro.hxx> +#include <TopoDS_Shape.hxx> + +//! Returns sample bottle TopoDS_Shape +TopoDS_Shape MakeBottle(const Standard_Real theWidth, + const Standard_Real theyHeight, + const Standard_Real theThickness); + +#endif // MAKEBOTTLE_H diff --git a/samples/OCCTOverview/code/Ocaf.json b/samples/OCCTOverview/code/Ocaf.json new file mode 100644 index 0000000000..f84b2c5dba --- /dev/null +++ b/samples/OCCTOverview/code/Ocaf.json @@ -0,0 +1,53 @@ +{ + "OCAF": { + "1 Create": [{ + "text": "Create Box", + "function": "CreateBoxOcafSample", + "description": "" + }, + { + "text": "Create Cylinder", + "function": "CreateCylinderOcafSample", + "description": "" + } + ], + "2 Modify": [{ + "text": "Modify Box", + "function": "ModifyBoxOcafSample", + "description": "" + }, + { + "text": "Modify Cylinder", + "function": "ModifyCylinderOcafSample", + "description": "" + } + ], + "3 Action": [{ + "text": "Undo", + "function": "UndoOcafSample", + "description": "" + }, + { + "text": "Redo", + "function": "RedoOcafSample", + "description": "" + } + ], + "4 Data storage": [{ + "text": "Open OCAF", + "function": "DialogOpenOcafSample", + "description": "" + }, + { + "text": "Save binary OCAF", + "function": "DialogSaveBinOcafSample", + "description": "" + }, + { + "text": "Save XML OCAF", + "function": "DialogSaveXmlOcafSample", + "description": "" + } + ] + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/OcafSamples.cxx b/samples/OCCTOverview/code/OcafSamples.cxx new file mode 100644 index 0000000000..940b49a758 --- /dev/null +++ b/samples/OCCTOverview/code/OcafSamples.cxx @@ -0,0 +1,624 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "OcafSamples.h" + +#include "TOcaf_Application.h" +#include "TOcafFunction_BoxDriver.h" +#include "TOcafFunction_CylDriver.h" + +#include <TPrsStd_AISViewer.hxx> +#include <AIS_InteractiveContext.hxx> +#include <AIS_DisplayMode.hxx> +#include <TPrsStd_AISPresentation.hxx> +#include <TNaming_NamedShape.hxx> +#include <TDataStd_Integer.hxx> +#include <TDataStd_Real.hxx> +#include <TDataStd_Name.hxx> +#include <TFunction_Function.hxx> +#include <TFunction_DriverTable.hxx> +#include <TDF_ChildIterator.hxx> +#include <PCDM_StoreStatus.hxx> +#include <BinDrivers.hxx> +#include <XmlDrivers.hxx> + +void OcafSamples::Process (const TCollection_AsciiString& theSampleName) +{ + if (IsImportSample(theSampleName)) + { + myObject3d.Clear(); + } + myObject2d.Clear(); + myCode.Clear(); + myIsProcessed = Standard_False; + try + { + ExecuteSample(theSampleName); + } + catch (...) + { + TraceError(TCollection_AsciiString("Error in sample: ") + theSampleName); + } +} + +void OcafSamples::ClearExtra() +{ + myOcafDoc = nullptr; + myContext->RemoveAll(Standard_True); +} + +void OcafSamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "CreateOcafDocument") + CreateOcafDocument(); + else if (theSampleName == "CreateBoxOcafSample") + CreateBoxOcafSample(); + else if (theSampleName == "CreateCylinderOcafSample") + CreateCylinderOcafSample(); + else if (theSampleName == "ModifyBoxOcafSample") + ModifyBoxOcafSample(); + else if (theSampleName == "ModifyCylinderOcafSample") + ModifyCylinderOcafSample(); + else if (theSampleName == "UndoOcafSample") + UndoOcafSample(); + else if (theSampleName == "RedoOcafSample") + RedoOcafSample(); + else if (theSampleName == "DialogOpenOcafSample") + DialogOpenOcafSample(); + else if (theSampleName == "DialogSaveBinOcafSample") + DialogSaveBinOcafSample(); + else if (theSampleName == "DialogSaveXmlOcafSample") + DialogSaveXmlOcafSample(); + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +Standard_Boolean OcafSamples::IsExportSample (const TCollection_AsciiString& theSampleName) +{ + if (theSampleName == "DialogSaveBinOcafSample" || theSampleName == "DialogSaveXmlOcafSample") + { + return Standard_True; + } + else + { + return Standard_False; + } +} + +Standard_Boolean OcafSamples::IsImportSample (const TCollection_AsciiString& theSampleName) +{ + if (theSampleName == "DialogOpenOcafSample") + { + return Standard_True; + } + else + { + return Standard_False; + } +} + +Standard_Boolean OcafSamples::IsBinarySample (const TCollection_AsciiString& theSampleName) +{ + if (theSampleName == "DialogOpenOcafSample" || theSampleName == "DialogSaveBinOcafSample") + { + return Standard_True; + } + else + { + return Standard_False; + } +} + +Standard_Boolean OcafSamples::IsXmlSample (const TCollection_AsciiString& theSampleName) +{ + if (theSampleName == "DialogOpenOcafSample" || theSampleName == "DialogSaveXmlOcafSample") + { + return Standard_True; + } + else + { + return Standard_False; + } +} + +void OcafSamples::CreateOcafDocument() +{ + Handle(TOcaf_Application) anOcaf_Application = new TOcaf_Application; + anOcaf_Application->NewDocument("BinOcaf", myOcafDoc); + TPrsStd_AISViewer::New(myOcafDoc->Main(), myViewer); + + Handle(AIS_InteractiveContext) anAisContext; + TPrsStd_AISViewer::Find(myOcafDoc->Main(), anAisContext); + anAisContext->SetDisplayMode(AIS_Shaded, Standard_True); + myContext = anAisContext; + + // Set the maximum number of available "undo" actions + myOcafDoc->SetUndoLimit(10); +} + +void OcafSamples::CreateBoxOcafSample() +{ + // Open a new command (for undo) + myOcafDoc->NewCommand(); + + // A data structure for our box: + // the box itself is attached to the BoxLabel label (as his name and his function attribute) + // its arguments (dimensions: width, length and height; and position: x, y, z) + // are attached to the child labels of the box: + // 0:1 Box Label ---> Name ---> Named shape ---> Function + // 0:1:1 -- Width Label + // 0:1:2 -- Length Label + // 0:1:3 -- Height Label + // 0:1:4 -- X Label + // 0:1:5 -- Y Label + // 0:1:6 -- Z Label + + // Create a new label in the data structure for the box + TDF_Label aLabel = TDF_TagSource::NewChild(myOcafDoc->Main()); + + Standard_Real aBoxWidth(30.0), aBoxLength(20.0), aBoxHeight(10.0); + Standard_Real aBoxX(0.0), aBoxY(0.0), aBoxZ(0.0); + Standard_CString aBoxName("OcafBox"); + // Create the data structure : Set the dimensions, position and name attributes + TDataStd_Real::Set(aLabel.FindChild(1), aBoxWidth); + TDataStd_Real::Set(aLabel.FindChild(2), aBoxLength); + TDataStd_Real::Set(aLabel.FindChild(3), aBoxHeight); + TDataStd_Real::Set(aLabel.FindChild(4), aBoxX); + TDataStd_Real::Set(aLabel.FindChild(5), aBoxY); + TDataStd_Real::Set(aLabel.FindChild(6), aBoxZ); + TDataStd_Name::Set(aLabel, aBoxName); // Name + + // Instantiate a TFunction_Function attribute connected to the current box driver + // and attach it to the data structure as an attribute of the Box Label + Handle(TFunction_Function) myFunction = TFunction_Function::Set(aLabel, TOcafFunction_BoxDriver::GetID()); + + // Initialize and execute the box driver (look at the "Execute()" code) + Handle(TFunction_Logbook) aLogBook = TFunction_Logbook::Set(aLabel); + + Handle(TFunction_Driver) myBoxDriver; + // Find the TOcafFunction_BoxDriver in the TFunction_DriverTable using its GUID + if (!TFunction_DriverTable::Get()->FindDriver(TOcafFunction_BoxDriver::GetID(), myBoxDriver)) + { + myResult << "Ocaf Box driver not found" << std::endl; + } + + myBoxDriver->Init(aLabel); + if (myBoxDriver->Execute(aLogBook)) + { + myResult << "Create Box function execute failed" << std::endl; + } + + // Get the TPrsStd_AISPresentation of the new box TNaming_NamedShape + Handle(TPrsStd_AISPresentation) anAisPresentation = TPrsStd_AISPresentation::Set(aLabel, TNaming_NamedShape::GetID()); + // Display it + anAisPresentation->Display(1); + // Attach an integer attribute to aLabel to memorize it's displayed + TDataStd_Integer::Set(aLabel, 1); + myContext->UpdateCurrentViewer(); + + // Close the command (for undo) + myOcafDoc->CommitCommand(); + + myResult << "Created a box with name: " << aBoxName << std::endl; + myResult << "base coord X: " << aBoxX << " Y: " << aBoxY << " Z: " << aBoxZ << std::endl; + myResult << "width: " << aBoxWidth << " length: " << aBoxLength << " height: " << aBoxHeight << std::endl; +} + +void OcafSamples::CreateCylinderOcafSample() +{ + // Open a new command (for undo) + myOcafDoc->NewCommand(); + + // A data structure for our cylinder: + // the cylinder itself is attached to the CylinderLabel label (as his name and his function attribute) + // its arguments (dimensions: radius and height; and position: x, y, z) + // are attached to the child labels of the cylinder: + // 0:1 Cylinder Label ---> Name ---> Named shape ---> Function + // 0:1:1 -- Radius Label + // 0:1:2 -- Height Label + // 0:1:3 -- X Label + // 0:1:4 -- Y Label + // 0:1:5 -- Z Label + + // Create a new label in the data structure for the cylinder + TDF_Label aLabel = TDF_TagSource::NewChild(myOcafDoc->Main()); + + Standard_Real aCylRadius(10.0), aCylHeight(20.0); + Standard_Real aCylX(60.0), aCylY(40.0), aCylZ(0.0); + Standard_CString aCylName("OcafCylinder"); + // Create the data structure : Set the dimensions, position and name attributes + TDataStd_Real::Set(aLabel.FindChild(1), aCylRadius); + TDataStd_Real::Set(aLabel.FindChild(2), aCylHeight); + TDataStd_Real::Set(aLabel.FindChild(3), aCylX); + TDataStd_Real::Set(aLabel.FindChild(4), aCylY); + TDataStd_Real::Set(aLabel.FindChild(5), aCylZ); + TDataStd_Name::Set(aLabel, aCylName); + + // Instantiate a TFunction_Function attribute connected to the current cylinder driver + // and attach it to the data structure as an attribute of the Cylinder Label + Handle(TFunction_Function) myFunction = TFunction_Function::Set(aLabel, TOcafFunction_CylDriver::GetID()); + + // Initialize and execute the cylinder driver (look at the "Execute()" code) + Handle(TFunction_Logbook) aLogBook = TFunction_Logbook::Set(aLabel); + + Handle(TFunction_Driver) myCylDriver; + // Find the TOcafFunction_CylDriver in the TFunction_DriverTable using its GUID + if (!TFunction_DriverTable::Get()->FindDriver(TOcafFunction_CylDriver::GetID(), myCylDriver)) + { + myResult << "Ocaf Cylinder driver not found"; + } + myCylDriver->Init(aLabel); + if (myCylDriver->Execute(aLogBook)) + { + myResult << "Create Cylinder function execute failed"; + } + // Get the TPrsStd_AISPresentation of the new box TNaming_NamedShape + Handle(TPrsStd_AISPresentation) anAisPresentation = TPrsStd_AISPresentation::Set(aLabel, TNaming_NamedShape::GetID()); + // Display it + anAisPresentation->Display(1); + // Attach an integer attribute to aLabel to memorize it's displayed + TDataStd_Integer::Set(aLabel, 1); + myContext->UpdateCurrentViewer(); + + // Close the command (for undo) + myOcafDoc->CommitCommand(); + + myResult << "Created a cylinder with name: " << aCylName << std::endl; + myResult << "radius: " << aCylRadius << " height: " << aCylHeight << std::endl; + myResult << "base coord X: " << aCylX << " Y: " << aCylY << " Z: " << aCylZ << std::endl; +} + +void OcafSamples::ModifyBoxOcafSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + Standard_Integer aBoxCount(0); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + // Get the main label of the selected object + Handle(TPrsStd_AISPresentation) anAisPresentation = Handle(TPrsStd_AISPresentation)::DownCast(anAisObject->GetOwner()); + TDF_Label aLabel = anAisPresentation->Label(); + + // Get the TFunction_Function attribute of the selected object + Handle(TFunction_Function) aFunction; + if (!aLabel.FindAttribute(TFunction_Function::GetID(), aFunction)) + { + myResult << "Object cannot be modify."; + return; + } + // Get the Standard_GUID of the TFunction_FunctionDriver of the selected object TFunction_Function attribute + Standard_GUID aDriverID = aFunction->GetDriverGUID(); + + // Case of a box created with the box function driver + if (aDriverID == TOcafFunction_BoxDriver::GetID()) + { + aBoxCount++; + Standard_Real aBoxX, aBoxY, aBoxZ, aBoxWidth, aBoxLength, aBoxHeight; + + // Get the attributes values of the current box + Handle(TDataStd_Real) aCurrentReal; + aLabel.FindChild(1).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxWidth = aCurrentReal->Get(); + aLabel.FindChild(2).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxLength = aCurrentReal->Get(); + aLabel.FindChild(3).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxHeight = aCurrentReal->Get(); + aLabel.FindChild(4).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxX = aCurrentReal->Get(); + aLabel.FindChild(5).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxY = aCurrentReal->Get(); + aLabel.FindChild(6).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aBoxZ = aCurrentReal->Get(); + Handle(TDataStd_Name) aBoxName; + aLabel.FindAttribute(TDataStd_Name::GetID(), aBoxName); + + myResult << "Current parameters of box with name: " << aBoxName->Get() << std::endl; + myResult << "width: " << aBoxWidth << " length: " << aBoxLength << " height: " << aBoxHeight << std::endl; + myResult << "base coord X: " << aBoxX << " Y: " << aBoxY << " Z: " << aBoxZ << std::endl; + + // Open a new command (for undo) + myOcafDoc->NewCommand(); + // Modify the box - 1.5 times increase + aBoxWidth *= 1.5; aBoxLength *= 1.5; aBoxHeight *= 1.5; + + TDataStd_Real::Set(aLabel.FindChild(1), aBoxWidth); + TDataStd_Real::Set(aLabel.FindChild(2), aBoxLength); + TDataStd_Real::Set(aLabel.FindChild(3), aBoxHeight); + TDataStd_Real::Set(aLabel.FindChild(4), aBoxX); + TDataStd_Real::Set(aLabel.FindChild(5), aBoxY); + TDataStd_Real::Set(aLabel.FindChild(6), aBoxZ); + + // Get the TFunction_FunctionDriver GUID used with the TFunction_Function + aDriverID = aFunction->GetDriverGUID(); + Handle(TFunction_Logbook) aLogBook = TFunction_Logbook::Set(aLabel); + Handle(TFunction_Driver) aBoxDriver; + // Find the TOcafFunction_BoxDriver in the TFunction_DriverTable using its GUID + TFunction_DriverTable::Get()->FindDriver(aDriverID, aBoxDriver); + // Execute the cut if it must be (if an attribute changes) + aBoxDriver->Init(aLabel); + + // Set the box touched, it will be useful to recompute an object which used this box as attribute + aLogBook->SetTouched(aLabel); + if (aBoxDriver->Execute(aLogBook)) + { + myResult << "Recompute failed" << std::endl; + } + + // Get the presentation of the box, display it and set it selected + anAisPresentation = TPrsStd_AISPresentation::Set(aLabel, TNaming_NamedShape::GetID()); + TDataStd_Integer::Set(aLabel, 1); + anAisPresentation->Display(1); + myContext->UpdateCurrentViewer(); + // Close the command (for undo) + myOcafDoc->CommitCommand(); + + myResult << std::endl; + myResult << "New box parameters: " << std::endl; + myResult << "base coord X: " << aBoxX << " Y: " << aBoxY << " Z: " << aBoxZ << std::endl; + myResult << "width: " << aBoxWidth << " length: " << aBoxLength << " height: " << aBoxHeight << std::endl; + } + } + if (aBoxCount) + { + myResult << "Number of modified boxes: " << aBoxCount << std::endl; + } + else + { + myResult << "No boxes to modify" << std::endl; + } +} + +void OcafSamples::ModifyCylinderOcafSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + Standard_Integer aCylCount(0); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + // Get the main label of the selected object + Handle(TPrsStd_AISPresentation) anAisPresentation = Handle(TPrsStd_AISPresentation)::DownCast(anAisObject->GetOwner()); + TDF_Label aLabel = anAisPresentation->Label(); + + // Get the TFunction_Function attribute of the selected object + Handle(TFunction_Function) aFunction; + if (!aLabel.FindAttribute(TFunction_Function::GetID(), aFunction)) + { + myResult << "Object cannot be modify."; + return; + } + // Get the Standard_GUID of the TFunction_FunctionDriver of the selected object TFunction_Function attribute + Standard_GUID aDriverID = aFunction->GetDriverGUID(); + + // Case of a box created with the box function driver + if (aDriverID == TOcafFunction_CylDriver::GetID()) + { + aCylCount++; + Standard_Real aCylRadius, aCylHeight, aCylX, aCylY, aCylZ; + + // Get the attributes values of the current box + Handle(TDataStd_Real) aCurrentReal; + aLabel.FindChild(1).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aCylRadius = aCurrentReal->Get(); + aLabel.FindChild(2).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aCylHeight = aCurrentReal->Get(); + aLabel.FindChild(3).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aCylX = aCurrentReal->Get(); + aLabel.FindChild(4).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aCylY = aCurrentReal->Get(); + aLabel.FindChild(5).FindAttribute(TDataStd_Real::GetID(), aCurrentReal); + aCylZ = aCurrentReal->Get(); + + Handle(TDataStd_Name) aCylName; + aLabel.FindAttribute(TDataStd_Name::GetID(), aCylName); + + myResult << "Current parameters of box with name: " << aCylName->Get() << std::endl; + myResult << "radius: " << aCylRadius << " height: " << aCylHeight << std::endl; + myResult << "base coord X: " << aCylX << " Y: " << aCylY << " Z: " << aCylZ << std::endl; + + // Open a new command (for undo) + myOcafDoc->NewCommand(); + // Modify the cylinder - 2x increase + aCylRadius *= 2.0; aCylHeight *= 2.0; + // and move base point in XY plane + aCylX *= 2.0; aCylY *= 2.0; + + TDataStd_Real::Set(aLabel.FindChild(1), aCylRadius); + TDataStd_Real::Set(aLabel.FindChild(2), aCylHeight); + TDataStd_Real::Set(aLabel.FindChild(3), aCylX); + TDataStd_Real::Set(aLabel.FindChild(4), aCylY); + TDataStd_Real::Set(aLabel.FindChild(5), aCylZ); + + // Get the TFunction_FunctionDriver GUID used with the TFunction_Function + aDriverID = aFunction->GetDriverGUID(); + Handle(TFunction_Logbook) aLogBook = TFunction_Logbook::Set(aLabel); + Handle(TFunction_Driver) aCylDriver; + // Find the TOcafFunction_CylDriver in the TFunction_DriverTable using its GUID + TFunction_DriverTable::Get()->FindDriver(aDriverID, aCylDriver); + // Execute the cut if it must be (if an attribute changes) + aCylDriver->Init(aLabel); + + // Set the cylinder touched, it will be useful to recompute an object which used this box as attribute + aLogBook->SetTouched(aLabel); + if (aCylDriver->Execute(aLogBook)) + { + myResult << "Recompute failed" << std::endl; + } + // Get the presentation of the box, display it and set it selected + anAisPresentation = TPrsStd_AISPresentation::Set(aLabel, TNaming_NamedShape::GetID()); + TDataStd_Integer::Set(aLabel, 1); + anAisPresentation->Display(1); + myContext->UpdateCurrentViewer(); + // Close the command (for undo) + myOcafDoc->CommitCommand(); + + myResult << std::endl; + myResult << "New cylinder parameters: " << std::endl; + myResult << "radius: " << aCylRadius << " height: " << aCylHeight << std::endl; + myResult << "base coord X: " << aCylX << " Y: " << aCylY << " Z: " << aCylZ << std::endl; + } + } + if (aCylCount) + { + myResult << "Number of modified boxes: " << aCylCount << std::endl; + } + else + { + myResult << "No boxes to modify" << std::endl; + } +} + +void OcafSamples::UndoOcafSample() +{ + if (myOcafDoc->Undo()) + { + myOcafDoc->CommitCommand(); + myContext->UpdateCurrentViewer(); + myResult << "Undo was done successfully" << std::endl; + } + else + { + myResult << "Nothing to undo" << std::endl; + } +} + +void OcafSamples::RedoOcafSample() +{ + if (myOcafDoc->Redo()) + { + myOcafDoc->CommitCommand(); + myContext->UpdateCurrentViewer(); + myResult << "Redo was done successfully" << std::endl; + } + else + { + myResult << "Nothing to redo" << std::endl; + } +} + +void OcafSamples::DialogOpenOcafSample() +{ + Handle(TOcaf_Application) anOcaf_Application = new TOcaf_Application; + // load persistence + BinDrivers::DefineFormat(anOcaf_Application); + XmlDrivers::DefineFormat(anOcaf_Application); + // Look for already opened + if (anOcaf_Application->IsInSession(myFileName)) + { + myResult << "Document: " << myFileName << " is already in session" << std::endl; + return; + } + // Open the document in the current application + PCDM_ReaderStatus aReaderStatus = anOcaf_Application->Open(myFileName, myOcafDoc); + if (aReaderStatus == PCDM_ReaderStatus::PCDM_RS_OK) + { + // Connect the document CAF (myDoc) with the AISContext (myAISContext) + TPrsStd_AISViewer::New(myOcafDoc->Main(), myViewer); + myOcafDoc->SetUndoLimit(10); + + myContext->RemoveAll(Standard_False); + Handle(AIS_InteractiveContext) aContext; + TPrsStd_AISViewer::Find(myOcafDoc->Main(), aContext); + aContext->SetDisplayMode(AIS_Shaded, Standard_True); + myContext = aContext; + + // Display the presentations (which was not stored in the document) + DisplayPresentation(); + myResult << "Open a document" << std::endl; + } + else + { + myResult << "Error! The file wasn't opened. PCDM_ReaderStatus: " << aReaderStatus << std::endl; + } +} + +void OcafSamples::DialogSaveBinOcafSample() +{ + Handle(TOcaf_Application) anOcaf_Application = new TOcaf_Application; + BinDrivers::DefineFormat(anOcaf_Application); + myOcafDoc->ChangeStorageFormat("BinOcaf"); + // Saves the document in the current application + PCDM_StoreStatus aStoreStatus = anOcaf_Application->SaveAs(myOcafDoc, myFileName); + if (aStoreStatus == PCDM_StoreStatus::PCDM_SS_OK) + { + myResult << "The file was saved successfully" << std::endl; + } + else + { + myResult << "Error! The file wasn't saved. PCDM_StoreStatus: " << aStoreStatus << std::endl; + } +} + +void OcafSamples::DialogSaveXmlOcafSample() +{ + Handle(TOcaf_Application) anOcaf_Application = new TOcaf_Application; + XmlDrivers::DefineFormat(anOcaf_Application); + myOcafDoc->ChangeStorageFormat("XmlOcaf"); + // Saves the document in the current application + PCDM_StoreStatus aStoreStatus = anOcaf_Application->SaveAs(myOcafDoc, myFileName); + if (aStoreStatus == PCDM_StoreStatus::PCDM_SS_OK) + { + myResult << "The file was saved successfully" << std::endl; + } + else + { + myResult << "Error! The file wasn't saved. PCDM_StoreStatus: " << aStoreStatus << std::endl; + } +} + +void OcafSamples::DisplayPresentation() +{ + TDF_Label aRootlabel = myOcafDoc->Main(); + + for (TDF_ChildIterator it(aRootlabel); it.More(); it.Next()) + { + TDF_Label aLabel = it.Value(); + Handle(TNaming_NamedShape) aNamedShape; + if (!aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNamedShape)) + { + continue; + } + Handle(TDataStd_Integer) aDataInteger; + + // To know if the object was displayed + if (aLabel.FindAttribute(TDataStd_Integer::GetID(), aDataInteger)) + { + if (!aDataInteger->Get()) + { + continue; + } + } + Handle(TPrsStd_AISPresentation) anAisPresentation; + if (!aLabel.FindAttribute(TPrsStd_AISPresentation::GetID(), anAisPresentation)) + { + anAisPresentation = TPrsStd_AISPresentation::Set(aLabel, TNaming_NamedShape::GetID()); + } + anAisPresentation->SetColor(Quantity_NOC_ORANGE); + anAisPresentation->Display(1); + } + myContext->UpdateCurrentViewer(); +} diff --git a/samples/OCCTOverview/code/OcafSamples.h b/samples/OCCTOverview/code/OcafSamples.h new file mode 100644 index 0000000000..73bf742a34 --- /dev/null +++ b/samples/OCCTOverview/code/OcafSamples.h @@ -0,0 +1,85 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef OCAFSAMPLES_H +#define OCAFSAMPLES_H + +#include "BaseSample.h" +#include "TOcaf_Application.h" + +#include <AIS_InteractiveContext.hxx> +#include <V3d_Viewer.hxx> +#include <TDocStd_Document.hxx> + +//! Implements OCAF samples +class OcafSamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(OcafSamples, BaseSample) +public: + + OcafSamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(V3d_Viewer)& theViewer, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample (theSampleSourcePath, theContext), + myViewer (theViewer) + { + // + } + + enum ExchangeType { None, Binary, Xml }; + + virtual void Process (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + + void ClearExtra(); + void SetFileName (const TCollection_AsciiString& theFileName) { myFileName = theFileName; }; + + static Standard_Boolean IsExportSample (const TCollection_AsciiString& theSampleName); + static Standard_Boolean IsImportSample (const TCollection_AsciiString& theSampleName); + static Standard_Boolean IsBinarySample (const TCollection_AsciiString& theSampleName); + static Standard_Boolean IsXmlSample (const TCollection_AsciiString& theSampleName); + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + // One function for every sample + void CreateOcafDocument(); + void CreateBoxOcafSample(); + void CreateCylinderOcafSample(); + void ModifyBoxOcafSample(); + void ModifyCylinderOcafSample(); + void UndoOcafSample(); + void RedoOcafSample(); + void DialogOpenOcafSample(); + void DialogSaveBinOcafSample(); + void DialogSaveXmlOcafSample(); + void DisplayPresentation(); + +private: + + ExchangeType myExchangeType; + TCollection_AsciiString myFileName; + Handle(V3d_Viewer) myViewer; + Handle(TDocStd_Document) myOcafDoc; + +}; + +#endif //OCAFSAMPLES_H diff --git a/samples/OCCTOverview/code/Sample2D_Face.cxx b/samples/OCCTOverview/code/Sample2D_Face.cxx new file mode 100644 index 0000000000..2e09ce0990 --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Face.cxx @@ -0,0 +1,486 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Sample2D_Face.h" + +#include <BRep_Tool.hxx> +#include <BRepAdaptor_Curve2d.hxx> +#include <GCPnts_QuasiUniformDeflection.hxx> +#include <GeomLib.hxx> +#include <Select3D_SensitiveGroup.hxx> +#include <Select3D_SensitiveCurve.hxx> +#include <SelectMgr_EntityOwner.hxx> +#include <TopExp_Explorer.hxx> +#include <TopoDS.hxx> + +Sample2D_Face::Sample2D_Face (const TopoDS_Shape& theFace) +: myFORWARDColor (Quantity_NOC_BLUE1), + myREVERSEDColor (Quantity_NOC_YELLOW), + myINTERNALColor (Quantity_NOC_RED1), + myEXTERNALColor (Quantity_NOC_MAGENTA1), + myWidthIndex (1), + myTypeIndex (1), + // + myshape (theFace), + myForwardNum (0), + myReversedNum (0), + myInternalNum (0), + myExternalNum (0), + // + myForwardBounds (0), + myReversedBounds (0), + myInternalBounds (0), + myExternalBounds (0) +{ + SetAutoHilight(Standard_False); + FillData(Standard_True); +} + +void Sample2D_Face::DrawMarker (const Handle(Geom2d_TrimmedCurve)& theCurve, + const Handle(Prs3d_Presentation)& thePresentation) +{ + Standard_Real aCenterParam = (theCurve->FirstParameter() + theCurve->LastParameter()) / 2; + gp_Pnt2d p; + gp_Vec2d v; + theCurve->D1(aCenterParam, p, v); + if (v.Magnitude() > gp::Resolution()) + { + gp_Vec aDir(v.X(), v.Y(), 0.); + gp_Pnt aPoint(p.X(), p.Y(), 0.); + aDir.Normalize(); + aDir.Reverse(); + gp_Dir aZ(0, 0, 1); + gp_Pnt aLeft (aPoint.Translated(aDir.Rotated(gp_Ax1(aPoint, aZ), M_PI / 6) * 5)); + gp_Pnt aRight(aPoint.Translated(aDir.Rotated(gp_Ax1(aPoint, aZ), M_PI * 11 / 6) * 5)); + + Handle(Graphic3d_ArrayOfPolylines) anArrow = new Graphic3d_ArrayOfPolylines(3); + anArrow->AddVertex(aLeft); + anArrow->AddVertex(aPoint); + anArrow->AddVertex(aRight); + + thePresentation->CurrentGroup()->AddPrimitiveArray(anArrow); + } +} + +void Sample2D_Face::FillData(Standard_Boolean isSizesRecompute) +{ + if (myshape.IsNull() || myshape.ShapeType() != TopAbs_FACE) + { + return; + } + + Standard_Real f, l; + TopoDS_Face aFace = TopoDS::Face(myshape); + + // count number of vertices and bounds in primitive arrays + if (isSizesRecompute) + { + mySeq_FORWARD.Clear(); + mySeq_REVERSED.Clear(); + mySeq_INTERNAL.Clear(); + mySeq_EXTERNAL.Clear(); + + myshape.Orientation(TopAbs_FORWARD); + for (TopExp_Explorer anEdgeIter (myshape, TopAbs_EDGE); anEdgeIter.More(); anEdgeIter.Next()) + { + const TopoDS_Edge& anEdge = TopoDS::Edge (anEdgeIter.Current()); + BRepAdaptor_Curve2d aCurveOnEdge (anEdge, aFace); + GCPnts_QuasiUniformDeflection anEdgeDistrib(aCurveOnEdge, 1.e-2); + if (!anEdgeDistrib.IsDone()) + { + continue; + } + + switch (anEdge.Orientation()) + { + case TopAbs_FORWARD: + { + myForwardNum += anEdgeDistrib.NbPoints(); + myForwardBounds++; + break; + } + case TopAbs_REVERSED: + { + myReversedNum += anEdgeDistrib.NbPoints(); + myReversedBounds++; + break; + } + case TopAbs_INTERNAL: + { + myInternalNum += anEdgeDistrib.NbPoints(); + myInternalBounds++; + break; + } + case TopAbs_EXTERNAL: + { + myExternalNum += anEdgeDistrib.NbPoints(); + myExternalBounds++; + break; + } + } + } + } + + myForwardArray = new Graphic3d_ArrayOfPolylines(myForwardNum, myForwardBounds); + myReversedArray = new Graphic3d_ArrayOfPolylines(myReversedNum, myReversedBounds); + myInternalArray = new Graphic3d_ArrayOfPolylines(myInternalNum, myInternalBounds); + myExternalArray = new Graphic3d_ArrayOfPolylines(myExternalNum, myExternalBounds); + + // fill primitive arrays + for (TopExp_Explorer anEdgeIter (myshape, TopAbs_EDGE); anEdgeIter.More(); anEdgeIter.Next()) + { + const TopoDS_Edge& anEdge = TopoDS::Edge (anEdgeIter.Current()); + const Handle(Geom2d_Curve) aCurve = BRep_Tool::CurveOnSurface (anEdge, aFace, f, l); + Handle(Geom2d_TrimmedCurve) aTrimmedCurve = new Geom2d_TrimmedCurve(aCurve, f, l); + if (!aTrimmedCurve.IsNull()) + { + Handle(Geom_Curve) aCurve3d = GeomLib::To3d(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), aTrimmedCurve); + BRepAdaptor_Curve2d aCurveOnEdge (anEdge, aFace); + GCPnts_QuasiUniformDeflection anEdgeDistrib (aCurveOnEdge, 1.e-2); + if (!anEdgeDistrib.IsDone()) + { + continue; + } + + switch (anEdge.Orientation()) + { + case TopAbs_FORWARD: + { + myForwardArray->AddBound(anEdgeDistrib.NbPoints()); + for (Standard_Integer i = 1; i <= anEdgeDistrib.NbPoints(); ++i) + { + myForwardArray->AddVertex(anEdgeDistrib.Value(i)); + } + if (isSizesRecompute) + { + mySeq_FORWARD.Append(aCurve3d); + } + break; + } + case TopAbs_REVERSED: + { + myReversedArray->AddBound(anEdgeDistrib.NbPoints()); + for (Standard_Integer i = 1; i <= anEdgeDistrib.NbPoints(); ++i) + { + myReversedArray->AddVertex(anEdgeDistrib.Value(i)); + } + if (isSizesRecompute) + { + mySeq_REVERSED.Append(aCurve3d); + } + break; + } + case TopAbs_INTERNAL: + { + myInternalArray->AddBound(anEdgeDistrib.NbPoints()); + for (Standard_Integer i = 1; i <= anEdgeDistrib.NbPoints(); ++i) + { + myInternalArray->AddVertex(anEdgeDistrib.Value(i)); + } + if (isSizesRecompute) + { + mySeq_INTERNAL.Append(aCurve3d); + } + break; + } + case TopAbs_EXTERNAL: + { + myExternalArray->AddBound(anEdgeDistrib.NbPoints()); + for (Standard_Integer i = 1; i <= anEdgeDistrib.NbPoints(); ++i) + { + myExternalArray->AddVertex(anEdgeDistrib.Value(i)); + } + if (isSizesRecompute) + { + mySeq_EXTERNAL.Append(aCurve3d); + } + break; + } + } + } + } +} + +void Sample2D_Face::Compute (const Handle(PrsMgr_PresentationManager3d)& , + const Handle(Prs3d_Presentation)& thePresentation, + const Standard_Integer theMode) +{ + if (theMode != 0) + { + return; + } + + thePresentation->Clear(); + myDrawer->SetWireDraw(1); + + if (myshape.IsNull() || myshape.ShapeType() != TopAbs_FACE) + { + return; + } + + Handle(Graphic3d_AspectLine3d) aLineAspect_FORWARD = new Graphic3d_AspectLine3d(myFORWARDColor, Aspect_TOL_SOLID, 1); + Handle(Graphic3d_AspectLine3d) aLineAspect_REVERSED = new Graphic3d_AspectLine3d(myREVERSEDColor, Aspect_TOL_SOLID, 1); + Handle(Graphic3d_AspectLine3d) aLineAspect_INTERNAL = new Graphic3d_AspectLine3d(myINTERNALColor, Aspect_TOL_SOLID, 1); + Handle(Graphic3d_AspectLine3d) aLineAspect_EXTERNAL = new Graphic3d_AspectLine3d(myEXTERNALColor, Aspect_TOL_SOLID, 1); + + Standard_Real f, l; + TopoDS_Face aFace = TopoDS::Face(myshape); + // estimating number of vertices in primitive arrays + for (TopExp_Explorer anEdgeIter (myshape, TopAbs_EDGE); anEdgeIter.More(); anEdgeIter.Next()) + { + const TopoDS_Edge& anEdge = TopoDS::Edge(anEdgeIter.Current()); + const Handle(Geom2d_Curve) aCurve = BRep_Tool::CurveOnSurface (anEdge, aFace, f, l); + + Handle(Geom2d_TrimmedCurve) aTrimmedCurve = new Geom2d_TrimmedCurve(aCurve, f, l); + // make a 3D curve from 2D trimmed curve to display it + Handle(Geom_Curve) aCurve3d = GeomLib::To3d(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), aTrimmedCurve); + // make distribution of points + BRepAdaptor_Curve2d aCurveOnEdge (anEdge, aFace); + GCPnts_QuasiUniformDeflection anEdgeDistrib(aCurveOnEdge, 1.e-2); + if (anEdgeDistrib.IsDone()) + { + switch (anEdge.Orientation()) + { + case TopAbs_FORWARD: + { + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_FORWARD); + DrawMarker(aTrimmedCurve, thePresentation); + break; + } + case TopAbs_REVERSED: + { + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_REVERSED); + DrawMarker(aTrimmedCurve, thePresentation); + break; + } + case TopAbs_INTERNAL: + { + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_INTERNAL); + DrawMarker(aTrimmedCurve, thePresentation); + + mySeq_INTERNAL.Append(aCurve3d); + break; + } + case TopAbs_EXTERNAL: + { + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_EXTERNAL); + DrawMarker(aTrimmedCurve, thePresentation); + break; + } + } + } + } + + // add all primitives to the presentation + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_FORWARD); + thePresentation->CurrentGroup()->AddPrimitiveArray(myForwardArray); + + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_REVERSED); + thePresentation->CurrentGroup()->AddPrimitiveArray(myReversedArray); + + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_INTERNAL); + thePresentation->CurrentGroup()->AddPrimitiveArray(myInternalArray); + + thePresentation->CurrentGroup()->SetPrimitivesAspect(aLineAspect_EXTERNAL); + thePresentation->CurrentGroup()->AddPrimitiveArray(myExternalArray); +} + +void Sample2D_Face::HilightSelected (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const SelectMgr_SequenceOfOwner& theOwners) +{ + Handle(Prs3d_Presentation) aSelectionPrs = GetSelectPresentation (thePrsMgr); + + Handle(Graphic3d_AspectLine3d) aLineAspect = new Graphic3d_AspectLine3d(Quantity_NOC_ANTIQUEWHITE, Aspect_TOL_SOLID, 2); + if (HasPresentation()) + { + aSelectionPrs->SetTransformPersistence(Presentation()->TransformPersistence()); + } + + const Standard_Integer aLength = theOwners.Length(); + aSelectionPrs->Clear(); + FillData(); + + Handle(Graphic3d_Group) aSelectGroup = aSelectionPrs->NewGroup(); + + for (Standard_Integer i = 1; i <= aLength; ++i) + { + Handle(SelectMgr_EntityOwner) anOwner = theOwners.Value(i); + // check priority of owner to add primitives in one of array + // containing primitives with certain type of orientation + switch (anOwner->Priority()) + { + case 7: + { + // add to objects with forward orientation + aSelectGroup->SetGroupPrimitivesAspect(aLineAspect); + aSelectGroup->AddPrimitiveArray(myForwardArray); + break; + } + case 6: + { + // add to objects with reversed orientation + aSelectGroup->SetGroupPrimitivesAspect(aLineAspect); + aSelectGroup->AddPrimitiveArray(myReversedArray); + break; + } + case 5: + { + // add to objects with internal orientation + aSelectGroup->SetGroupPrimitivesAspect(aLineAspect); + aSelectGroup->AddPrimitiveArray(myInternalArray); + break; + } + case 4: + { + // add to objects with external orientation + aSelectGroup->SetGroupPrimitivesAspect(aLineAspect); + aSelectGroup->AddPrimitiveArray(myExternalArray); + break; + } + } + } + aSelectionPrs->Display(); +} + +void Sample2D_Face::ClearSelected() +{ + if (Handle(Prs3d_Presentation) aSelectionPrs = GetSelectPresentation(NULL)) + { + aSelectionPrs->Clear(); + } +} + +void Sample2D_Face::HilightOwnerWithColor (const Handle(PrsMgr_PresentationManager3d)& thePM, + const Handle(Prs3d_Drawer)& theStyle, + const Handle(SelectMgr_EntityOwner)& theOwner) +{ + Handle(Prs3d_Presentation) aHighlightPrs = GetHilightPresentation(thePM); + if (HasPresentation()) + { + aHighlightPrs->SetTransformPersistence(Presentation()->TransformPersistence()); + } + if (theOwner.IsNull()) + { + return; + } + + aHighlightPrs->Clear(); + FillData(); + + // Direct highlighting + aHighlightPrs->NewGroup(); + Handle(Graphic3d_Group) aHilightGroup = aHighlightPrs->CurrentGroup(); + Handle(Graphic3d_AspectLine3d) aLineAspect = new Graphic3d_AspectLine3d(theStyle->Color(), Aspect_TOL_SOLID, 2); + switch (theOwner->Priority()) + { + case 7: + { + aHilightGroup->SetGroupPrimitivesAspect(aLineAspect); + aHilightGroup->AddPrimitiveArray(myForwardArray); + break; + } + case 6: + { + aHilightGroup->SetGroupPrimitivesAspect(aLineAspect); + aHilightGroup->AddPrimitiveArray(myReversedArray); + break; + } + case 5: + { + aHilightGroup->SetGroupPrimitivesAspect(aLineAspect); + aHilightGroup->AddPrimitiveArray(myInternalArray); + break; + } + case 4: + { + aHilightGroup->SetGroupPrimitivesAspect(aLineAspect); + aHilightGroup->AddPrimitiveArray(myExternalArray); + break; + } + } + if (thePM->IsImmediateModeOn()) + { + thePM->AddToImmediateList(aHighlightPrs); + } +} + +void Sample2D_Face::ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, + const Standard_Integer theMode) +{ + if (myshape.IsNull() + || theMode != 0) + { + return; + } + + if (mySeq_FORWARD.IsEmpty() + && mySeq_REVERSED.IsEmpty() + && mySeq_INTERNAL.IsEmpty() + && mySeq_EXTERNAL.IsEmpty()) + { + return; + } + + // create entity owner for every part of the face + // set different priorities for primitives of different orientation + Handle(SelectMgr_EntityOwner) anOwner_Forward = new SelectMgr_EntityOwner(this, 7); + Handle(SelectMgr_EntityOwner) anOwner_Reversed = new SelectMgr_EntityOwner(this, 6); + Handle(SelectMgr_EntityOwner) anOwner_Internal = new SelectMgr_EntityOwner(this, 5); + Handle(SelectMgr_EntityOwner) anOwner_External = new SelectMgr_EntityOwner(this, 4); + + // create a sensitive for every part + Handle(Select3D_SensitiveGroup) aForwardGroup = new Select3D_SensitiveGroup(anOwner_Forward); + Handle(Select3D_SensitiveGroup) aReversedGroup = new Select3D_SensitiveGroup(anOwner_Reversed); + Handle(Select3D_SensitiveGroup) aInternalGroup = new Select3D_SensitiveGroup(anOwner_Internal); + Handle(Select3D_SensitiveGroup) aExternalGroup = new Select3D_SensitiveGroup(anOwner_External); + + Standard_Integer aLength = mySeq_FORWARD.Length(); + for (Standard_Integer i = 1; i <= aLength; ++i) + { + Handle(Select3D_SensitiveCurve) aSensitveCurve = new Select3D_SensitiveCurve(anOwner_Forward, mySeq_FORWARD(i)); + aForwardGroup->Add(aSensitveCurve); + } + theSelection->Add(aForwardGroup); + + aLength = mySeq_REVERSED.Length(); + for (Standard_Integer i = 1; i <= aLength; ++i) + { + Handle(Select3D_SensitiveCurve) aSensitveCurve = new Select3D_SensitiveCurve(anOwner_Reversed, mySeq_REVERSED(i)); + aReversedGroup->Add(aSensitveCurve); + } + theSelection->Add(aReversedGroup); + + aLength = mySeq_INTERNAL.Length(); + for (Standard_Integer i = 1; i <= aLength; ++i) + { + Handle(Select3D_SensitiveCurve) aSensitveCurve = new Select3D_SensitiveCurve(anOwner_Internal, mySeq_INTERNAL(i)); + aInternalGroup->Add(aSensitveCurve); + } + theSelection->Add(aInternalGroup); + + aLength = mySeq_EXTERNAL.Length(); + for (Standard_Integer i = 1; i <= aLength; ++i) + { + Handle(Select3D_SensitiveCurve) aSensitveCurve = new Select3D_SensitiveCurve(anOwner_External, mySeq_EXTERNAL(i)); + aExternalGroup->Add(aSensitveCurve); + } + theSelection->Add(aExternalGroup); +} diff --git a/samples/OCCTOverview/code/Sample2D_Face.h b/samples/OCCTOverview/code/Sample2D_Face.h new file mode 100644 index 0000000000..f88e9c2009 --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Face.h @@ -0,0 +1,107 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _Sample2D_Face_HeaderFile +#define _Sample2D_Face_HeaderFile + +#include <AIS_InteractiveObject.hxx> +#include <Geom2d_TrimmedCurve.hxx> +#include <Graphic3d_ArrayOfPolylines.hxx> +#include <TopoDS_Face.hxx> +#include <TColGeom_SequenceOfCurve.hxx> + +//! AIS interactive Object for sample 2D face +class Sample2D_Face : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(Sample2D_Face, AIS_InteractiveObject) +public: + + Standard_EXPORT Sample2D_Face (const TopoDS_Shape& theFace); + +public: + + TopoDS_Shape& Shape() { return myshape; } + void SetFace (const TopoDS_Shape& theFace) { myshape = theFace; } + +public: + + Quantity_Color myFORWARDColor; + Quantity_Color myREVERSEDColor; + Quantity_Color myINTERNALColor; + Quantity_Color myEXTERNALColor; + Standard_Integer myWidthIndex; + Standard_Integer myTypeIndex; + +private: + + //! Return TRUE for supported display modes (only mode 0 is supported). + virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; } + + //! Compute presentation. + virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection. + virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, + const Standard_Integer theMode) Standard_OVERRIDE; + + virtual void ClearSelected() Standard_OVERRIDE; + + //! Method for advanced customizable selection of picked object + virtual void HilightSelected (const Handle(PrsMgr_PresentationManager3d)& thePrsMgr, + const SelectMgr_SequenceOfOwner& theOwners) Standard_OVERRIDE; + + //! Method for advanced customizable highlighting of picked object. + virtual void HilightOwnerWithColor (const Handle(PrsMgr_PresentationManager3d)& thePM, + const Handle(Prs3d_Drawer)& theStyle, + const Handle(SelectMgr_EntityOwner)& theOwner) Standard_OVERRIDE; + + void DrawMarker (const Handle(Geom2d_TrimmedCurve)& theCurve, + const Handle(Prs3d_Presentation)& thePresentation); + + void FillData(Standard_Boolean isSizesRecomputed = Standard_False); + +private: + + TopoDS_Shape myshape; + TColGeom_SequenceOfCurve mySeq_FORWARD; + TColGeom_SequenceOfCurve mySeq_REVERSED; + TColGeom_SequenceOfCurve mySeq_INTERNAL; + TColGeom_SequenceOfCurve mySeq_EXTERNAL; + + Handle(Graphic3d_ArrayOfPolylines) myForwardArray; + Handle(Graphic3d_ArrayOfPolylines) myReversedArray; + Handle(Graphic3d_ArrayOfPolylines) myInternalArray; + Handle(Graphic3d_ArrayOfPolylines) myExternalArray; + + Standard_Integer myForwardNum; + Standard_Integer myReversedNum; + Standard_Integer myInternalNum; + Standard_Integer myExternalNum; + Standard_Integer myForwardBounds; + Standard_Integer myReversedBounds; + Standard_Integer myInternalBounds; + Standard_Integer myExternalBounds; + +}; + +#endif diff --git a/samples/OCCTOverview/code/Sample2D_Image.cxx b/samples/OCCTOverview/code/Sample2D_Image.cxx new file mode 100644 index 0000000000..3e833ee206 --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Image.cxx @@ -0,0 +1,88 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Sample2D_Image.h" + +#include <AIS_InteractiveContext.hxx> +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <BRepBuilderAPI_MakeWire.hxx> +#include <BRepBuilderAPI_MakeFace.hxx> +#include <gp_Pnt.hxx> +#include <Graphic3d_Texture1D.hxx> +#include <Graphic3d_Texture1Dsegment.hxx> +#include <Graphic3d_Texture2Dmanual.hxx> +#include <Image_AlienPixMap.hxx> +#include <Prs3d_ShadingAspect.hxx> +#include <TopoDS_Edge.hxx> +#include <TopoDS_Wire.hxx> + +Sample2D_Image::Sample2D_Image (const TCollection_AsciiString& theFileName, + const Standard_Real theX, + const Standard_Real theY, + const Standard_Real theScale) +: AIS_Shape (TopoDS_Shape()), + myFilename (theFileName), + myX (theX), + myY (theY), + myScale (theScale) +{ + // +} + +void Sample2D_Image::MakeShape() +{ + Standard_Real coeff = 1.0; + Handle(Image_AlienPixMap) anImage = new Image_AlienPixMap(); + if (anImage->Load (myFilename)) + { + coeff = Standard_Real(anImage->Height()) / Standard_Real(anImage->Width()) * myScale; + } + + TopoDS_Edge E1 = BRepBuilderAPI_MakeEdge (gp_Pnt(myX, myY, 0.), + gp_Pnt(100 * myScale + myX, myY, 0.)); + TopoDS_Edge E2 = BRepBuilderAPI_MakeEdge (gp_Pnt(100 * myScale + myX, myY, 0.), + gp_Pnt(100 * myScale + myX, 100 * coeff + myY, 0.)); + TopoDS_Edge E3 = BRepBuilderAPI_MakeEdge (gp_Pnt(100 * myScale + myX, 100 * coeff + myY, 0.), + gp_Pnt(myX, 100 * coeff + myY, 0.)); + TopoDS_Edge E4 = BRepBuilderAPI_MakeEdge (gp_Pnt(myX, 100 * coeff + myY, 0.), + gp_Pnt(myX, myY, 0.)); + TopoDS_Wire anImageBounds = BRepBuilderAPI_MakeWire(E1, E2, E3, E4); + myFace = BRepBuilderAPI_MakeFace(gp_Pln(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), anImageBounds); +} + +void Sample2D_Image::SetContext (const Handle(AIS_InteractiveContext)& theContext) +{ + if (theContext.IsNull() || theContext->CurrentViewer().IsNull()) + { + AIS_InteractiveObject::SetContext (theContext); + return; + } + + AIS_InteractiveObject::SetContext (theContext); + MakeShape(); + this->Set(TopoDS_Shape(myFace)); + + myDrawer->SetShadingAspect(new Prs3d_ShadingAspect()); + Handle(Graphic3d_Texture2Dmanual) aTexture = new Graphic3d_Texture2Dmanual(myFilename); + aTexture->DisableModulate(); + myDrawer->ShadingAspect()->Aspect()->SetTextureMap (aTexture); + myDrawer->ShadingAspect()->Aspect()->SetTextureMapOn(); +} diff --git a/samples/OCCTOverview/code/Sample2D_Image.h b/samples/OCCTOverview/code/Sample2D_Image.h new file mode 100644 index 0000000000..c3b9a886b4 --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Image.h @@ -0,0 +1,86 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _Sample2D_Image_HeaderFile +#define _Sample2D_Image_HeaderFile +#include <Standard_Macro.hxx> +#include <Standard_DefineHandle.hxx> + +#include <OSD_File.hxx> +#include <Standard_Boolean.hxx> +#include <Standard_CString.hxx> +#include <Standard_Integer.hxx> +#include <SelectMgr_Selection.hxx> +#include <Standard_OStream.hxx> +#include <Standard_IStream.hxx> +#include <AIS_Shape.hxx> +#include <TopoDS_Face.hxx> + +//! AIS shape for sample 2D image +class Sample2D_Image : public AIS_Shape +{ + DEFINE_STANDARD_RTTI_INLINE(Sample2D_Image, AIS_Shape) +public: + + //! Constructor. + Standard_EXPORT Sample2D_Image (const TCollection_AsciiString& theFileName, + const Standard_Real theX = 0.0, + const Standard_Real theY = 0.0, + const Standard_Real theScale = 1.0); + + //! Return image coordinates. + void GetCoord (Standard_Real& theX, Standard_Real& theY) const + { + theX = myX; + theY = myY; + } + + //! Return image coordinates. + void SetCoord (const Standard_Real theX, const Standard_Real theY) + { + myX = theX; + myY = theY; + } + + //! Return image scale factor. + Standard_Real GetScale() const { return myScale; } + + //! Set image scale factor. + void SetScale(const Standard_Real theNewScale) { myScale = theNewScale; } + + //! Assign new interactive context to the object. + Standard_EXPORT virtual void SetContext (const Handle(AIS_InteractiveContext)& theContext) Standard_OVERRIDE; + +private: + + void MakeShape(); + +protected: + + TopoDS_Face myFace; + TCollection_AsciiString myFilename; + Standard_Real myX; + Standard_Real myY; + Standard_Real myScale; + +}; + +#endif diff --git a/samples/OCCTOverview/code/Sample2D_Markers.cxx b/samples/OCCTOverview/code/Sample2D_Markers.cxx new file mode 100644 index 0000000000..6b6095fecc --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Markers.cxx @@ -0,0 +1,80 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Sample2D_Markers.h" + +#include <Aspect_TypeOfMarker.hxx> + +// generic marker +Sample2D_Markers::Sample2D_Markers (const Standard_Real theXPosition, + const Standard_Real theYPosition, + const Aspect_TypeOfMarker theMarkerType, + const Quantity_Color theColor, + const Standard_Real theScaleOrId) +: myArrayOfPoints (new Graphic3d_ArrayOfPoints(1)) +{ + myXPosition = theXPosition; + myYPosition = theYPosition; + myMarkerType = theMarkerType; + myColor = theColor; + myIndex = theScaleOrId; +} + +Sample2D_Markers::Sample2D_Markers (const Standard_Real theXPosition, + const Standard_Real theYPosition, + const Handle(Graphic3d_ArrayOfPoints)& theArrayOfPoints, + const Aspect_TypeOfMarker theMarkerType, + const Quantity_Color theColor, + const Standard_Real theScaleOrId) +: myArrayOfPoints (new Graphic3d_ArrayOfPoints(6)) +{ + myXPosition = theXPosition; + myYPosition = theYPosition; + myMarkerType = theMarkerType; + myColor = theColor; + myIndex = theScaleOrId; + myArrayOfPoints = theArrayOfPoints; +} + +void Sample2D_Markers::Compute (const Handle(PrsMgr_PresentationManager3d)& , + const Handle(Prs3d_Presentation)& thePrs, + const Standard_Integer theMode) +{ + if (theMode != 0) + { + return; + } + + if (myMarkerType == Aspect_TOM_USERDEFINED) + { + Handle(Graphic3d_AspectMarker3d) aMarker = new Graphic3d_AspectMarker3d(Aspect_TOM_POINT, myColor, myIndex); + thePrs->CurrentGroup()->SetGroupPrimitivesAspect(aMarker); + thePrs->CurrentGroup()->AddPrimitiveArray(myArrayOfPoints); + } + else + { + Handle(Graphic3d_AspectMarker3d) aMarker = new Graphic3d_AspectMarker3d(myMarkerType, myColor, myIndex); + thePrs->CurrentGroup()->SetPrimitivesAspect(aMarker); + Handle(Graphic3d_ArrayOfPoints) anArrayOfPoints = new Graphic3d_ArrayOfPoints(1); + anArrayOfPoints->AddVertex(myXPosition, myYPosition, 0); + thePrs->CurrentGroup()->AddPrimitiveArray(anArrayOfPoints); + } +} diff --git a/samples/OCCTOverview/code/Sample2D_Markers.h b/samples/OCCTOverview/code/Sample2D_Markers.h new file mode 100644 index 0000000000..5e77c43338 --- /dev/null +++ b/samples/OCCTOverview/code/Sample2D_Markers.h @@ -0,0 +1,88 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _Sample2D_Markers_HeaderFile +#define _Sample2D_Markers_HeaderFile + +#include <AIS_InteractiveObject.hxx> +#include <Graphic3d_ArrayOfPoints.hxx> + +//! AIS AIS interactive object for sample 2D marker +class Sample2D_Markers : public AIS_InteractiveObject +{ + DEFINE_STANDARD_RTTI_INLINE(Sample2D_Markers, AIS_InteractiveObject) +private: + enum Sample2D_CurrentTypeOfMarker + { + Sample2D_CTOM_Generic, + Sample2D_CTOM_Polyline, + Sample2D_CTOM_Circle, + Sample2D_CTOM_Ellips + }; + +public: + + //! Generic marker + Standard_EXPORT Sample2D_Markers (const Standard_Real theXPosition, + const Standard_Real theYPosition, + const Aspect_TypeOfMarker theMarkerType, + const Quantity_Color theColor, + const Standard_Real theScaleOrId=5.0); + + //! Polyline marker + Standard_EXPORT Sample2D_Markers (const Standard_Real theXPosition, + const Standard_Real theYPosition, + const Handle(Graphic3d_ArrayOfPoints)& theArrayOfPoints, + const Aspect_TypeOfMarker theMarkerType, + const Quantity_Color theColor, + const Standard_Real theScaleOrId=2.0); + +private: + + //! Return TRUE for supported display modes (only mode 0 is supported). + virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode == 0; } + + //! Compute presentation. + virtual void Compute (const Handle(PrsMgr_PresentationManager3d)& /*aPresentationManager*/, + const Handle(Prs3d_Presentation)& /*aPresentation*/, + const Standard_Integer theMode) Standard_OVERRIDE; + + //! Compute selection (not implemented). + virtual void ComputeSelection (const Handle(SelectMgr_Selection)& , + const Standard_Integer ) Standard_OVERRIDE {} + + virtual void SetContext(const Handle(AIS_InteractiveContext)& ) Standard_OVERRIDE {} + +private: + + Sample2D_CurrentTypeOfMarker myCurrentTypeOfMarker; + Standard_Real myXPosition; + Standard_Real myYPosition; + Aspect_TypeOfMarker myMarkerType; + Quantity_Color myColor; + Standard_Real myWidth; + Standard_Real myHeight; + Standard_Real myIndex; + //! specific polyline marker + Handle(Graphic3d_ArrayOfPoints) myArrayOfPoints; +}; + +#endif diff --git a/samples/OCCTOverview/code/Samples.qrc b/samples/OCCTOverview/code/Samples.qrc new file mode 100644 index 0000000000..59326e0751 --- /dev/null +++ b/samples/OCCTOverview/code/Samples.qrc @@ -0,0 +1,11 @@ +<RCC> + <qresource prefix="/menus"> + <file>Geometry.json</file> + <file>Topology.json</file> + <file>Triangulation.json</file> + <file>DataExchange.json</file> + <file>Viewer3d.json</file> + <file>Viewer2d.json</file> + <file>Ocaf.json</file> + </qresource> +</RCC> diff --git a/samples/OCCTOverview/code/TOcafFunction_BoxDriver.cxx b/samples/OCCTOverview/code/TOcafFunction_BoxDriver.cxx new file mode 100644 index 0000000000..6589efab1f --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_BoxDriver.cxx @@ -0,0 +1,148 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TOcafFunction_BoxDriver.h" + +#include <BRepPrimAPI_MakeBox.hxx> +#include <Standard_GUID.hxx> +#include <TDataStd_Real.hxx> +#include <TNaming_Builder.hxx> + +//======================================================================= +//function : GetID +//purpose : +//======================================================================= +const Standard_GUID& TOcafFunction_BoxDriver::GetID() +{ + static const Standard_GUID anID("22D22E51-D69A-11d4-8F1A-0060B0EE18E8"); + return anID; +} + +//======================================================================= +//function : Validate +//purpose : +//======================================================================= +void TOcafFunction_BoxDriver::Validate(Handle(TFunction_Logbook)& log) const +{ + // We validate the object label ( Label() ), all the arguments and the results of the object: + log->SetValid(Label(), Standard_True); +} + +//======================================================================= +//function : MustExecute +//purpose : +//======================================================================= +Standard_Boolean TOcafFunction_BoxDriver::MustExecute(const Handle(TFunction_Logbook)& log) const +{ + // If the object's label is modified: + if (log->IsModified(Label())) return Standard_True; + + // Cut (in our simple case) has two arguments: The original shape, and the tool shape. + // They are on the child labels of the box's label: + // So, OriginalNShape - is attached to the first child label + // ToolNShape - is attached to the second child label. + // + // Let's check them: + if (log->IsModified(Label().FindChild(1))) + { + return Standard_True; // width. + } + if (log->IsModified(Label().FindChild(2))) + { + return Standard_True; // length, + } + if (log->IsModified(Label().FindChild(3))) + { + return Standard_True; // width. + } + if (log->IsModified(Label().FindChild(4))) + { + return Standard_True; // length, + } + if (log->IsModified(Label().FindChild(5))) + { + return Standard_True; // width. + } + if (log->IsModified(Label().FindChild(6))) + { + return Standard_True; // length, + } + // if there are no any modifications concerned the box, + // it's not necessary to recompute (to call the method Execute()): + return Standard_False; +} + +//======================================================================= +//function : Execute +//purpose : +//======================================================================= +Standard_Integer TOcafFunction_BoxDriver::Execute(Handle(TFunction_Logbook)& /*log*/) const +{ + // Get the values of dimension and position attributes + Handle(TDataStd_Real) TSR; + Standard_Real x, y, z, l, h, w; + if (!Label().FindChild(1).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + l = TSR->Get(); + + if (!Label().FindChild(2).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + h = TSR->Get(); + + if (!Label().FindChild(3).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + w = TSR->Get(); + + if (!Label().FindChild(4).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + x = TSR->Get(); + + if (!Label().FindChild(5).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + y = TSR->Get(); + + if (!Label().FindChild(6).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + z = TSR->Get(); + + // Build a box using the dimension and position attributes + BRepPrimAPI_MakeBox mkBox(gp_Pnt(x, y, z), l, h, w); + TopoDS_Shape ResultShape = mkBox.Shape(); + + // Build a TNaming_NamedShape using built box + TNaming_Builder B(Label()); + B.Generated(ResultShape); + // That's all: + // If there are no any mistakes we return 0: + return 0; +} diff --git a/samples/OCCTOverview/code/TOcafFunction_BoxDriver.h b/samples/OCCTOverview/code/TOcafFunction_BoxDriver.h new file mode 100644 index 0000000000..bbeed55506 --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_BoxDriver.h @@ -0,0 +1,57 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _TOcafFunction_BoxDriver_HeaderFile +#define _TOcafFunction_BoxDriver_HeaderFile + +#include <TFunction_Driver.hxx> +#include <TFunction_Logbook.hxx> + +//! Creation of an instance of the box driver. It's possible (and recommended) +//! to have only one instance of a driver for the whole session. +class TOcafFunction_BoxDriver : public TFunction_Driver +{ + DEFINE_STANDARD_RTTI_INLINE(TOcafFunction_BoxDriver, TFunction_Driver) +public: + Standard_EXPORT static const Standard_GUID& GetID(); +public: + + TOcafFunction_BoxDriver() {} + + //! Validation of the object label, its arguments and its results. + Standard_EXPORT virtual void Validate (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We call this method to check if the object was modified to be invoked. + //! If the object label or an argument is modified, we must recompute the object - to call the method Execute(). + Standard_EXPORT virtual Standard_Boolean MustExecute (const Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We compute the object and topologically name it. + //! If during the execution we found something wrong, we return the number of the failure. + //! For example: + //! 1 - an attribute hasn't been found, + //! 2 - algorithm failed, + //! if there are no any mistakes occurred we return 0: + //! 0 - no mistakes were found. + Standard_EXPORT virtual Standard_Integer Execute (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + +}; + +#endif diff --git a/samples/OCCTOverview/code/TOcafFunction_CutDriver.cxx b/samples/OCCTOverview/code/TOcafFunction_CutDriver.cxx new file mode 100644 index 0000000000..cbbaca349b --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_CutDriver.cxx @@ -0,0 +1,152 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TOcafFunction_CutDriver.h" + +#include <TNaming_NamedShape.hxx> +#include <TNaming_Builder.hxx> + +#include <BRepAlgoAPI_Cut.hxx> +#include <Standard_GUID.hxx> +#include <TCollection_AsciiString.hxx> +#include <TDF_Tool.hxx> +#include <TDF_Reference.hxx> +#include <TFunction_Logbook.hxx> + +#include <Standard_WarningsDisable.hxx> +#include <QMessageBox> +#include <QApplication> +#include <QObject> +#include <Standard_WarningsRestore.hxx> + +//======================================================================= +//function : GetID +//purpose : +//======================================================================= +const Standard_GUID& TOcafFunction_CutDriver::GetID() +{ + static const Standard_GUID anID("22D22E52-D69A-11d4-8F1A-0060B0EE18E8"); + return anID; +} + +//======================================================================= +//function : Validate +//purpose : +//======================================================================= +void TOcafFunction_CutDriver::Validate (Handle(TFunction_Logbook)& log) const +{ + // We validate the object label ( Label() ), all the arguments and the results of the object: + log->SetValid(Label(), Standard_True); +} + +//======================================================================= +//function : MustExecute +//purpose : +//======================================================================= +Standard_Boolean TOcafFunction_CutDriver::MustExecute(const Handle(TFunction_Logbook)& log) const +{ + // If the object's label is modified: + if (log->IsModified(Label())) return Standard_True; + + // Cut (in our simple case) has two arguments: The original shape, and the tool shape. + // They are on the child labels of the cut's label: + // So, OriginalNShape - is attached to the first child label + // ToolNShape - is attached to the second child label, + // . + // Let's check them: + Handle(TDF_Reference) OriginalRef; + //TDF_Label aLabel = Label().FindChild(1); +/* + BOOL f = Label().IsNull(); + int a = Label().NbChildren(); +*/ + TCollection_AsciiString aEntry; + TDF_Tool::Entry(Label(), aEntry); + std::cout << "Entry: " << aEntry.ToCString() << std::endl; + Label().FindChild(1).FindAttribute(TDF_Reference::GetID(), OriginalRef); + if (log->IsModified(OriginalRef->Get())) return Standard_True; // Original shape. + + Handle(TDF_Reference) ToolRef; + Label().FindChild(2).FindAttribute(TDF_Reference::GetID(), ToolRef); + if (log->IsModified(ToolRef->Get())) return Standard_True; // Tool shape. + + // if there are no any modifications concerned the cut, + // it's not necessary to recompute (to call the method Execute()): + return Standard_False; +} + +//======================================================================= +//function : Execute +//purpose : +//======================================================================= +Standard_Integer TOcafFunction_CutDriver::Execute(Handle(TFunction_Logbook)& /*log*/) const +{ + // Let's get the arguments (OriginalNShape, ToolNShape of the object): + + // First, we have to retrieve the TDF_Reference attributes to obtain + // the root labels of the OriginalNShape and the ToolNShape: + Handle(TDF_Reference) OriginalRef, ToolRef; + if (!Label().FindChild(1).FindAttribute(TDF_Reference::GetID(), OriginalRef)) + { + return 1; + } + TDF_Label OriginalLab = OriginalRef->Get(); + if (!Label().FindChild(2).FindAttribute(TDF_Reference::GetID(), ToolRef)) + { + return 1; + } + TDF_Label ToolLab = ToolRef->Get(); + + // Get the TNaming_NamedShape attributes of these labels + Handle(TNaming_NamedShape) OriginalNShape, ToolNShape; + if (!(OriginalLab.FindAttribute(TNaming_NamedShape::GetID(), OriginalNShape))) + { + throw Standard_Failure("TOcaf_Commands::CutObjects"); + } + if (!(ToolLab.FindAttribute(TNaming_NamedShape::GetID(), ToolNShape))) + { + throw Standard_Failure("TOcaf_Commands::CutObjects"); + } + + // Now, let's get the TopoDS_Shape of these TNaming_NamedShape: + TopoDS_Shape OriginalShape = OriginalNShape->Get(); + TopoDS_Shape ToolShape = ToolNShape->Get(); + + // STEP 2: + // Let's call for algorithm computing a cut operation: + BRepAlgoAPI_Cut mkCut(OriginalShape, ToolShape); + // Let's check if the Cut has been successful: + if (!mkCut.IsDone()) + { + QMessageBox::critical(qApp->activeWindow(), + QObject::tr("Cut Function Driver"), + QObject::tr("Cut not done.")); + return 2; + } + TopoDS_Shape ResultShape = mkCut.Shape(); + + // Build a TNaming_NamedShape using built cut + TNaming_Builder B(Label()); + B.Modify(OriginalShape, ResultShape); + // That's all: + // If there are no any mistakes we return 0: + return 0; +} diff --git a/samples/OCCTOverview/code/TOcafFunction_CutDriver.h b/samples/OCCTOverview/code/TOcafFunction_CutDriver.h new file mode 100644 index 0000000000..9b25cecf95 --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_CutDriver.h @@ -0,0 +1,57 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _TOcafFunction_CutDriver_HeaderFile +#define _TOcafFunction_CutDriver_HeaderFile + +#include <TFunction_Driver.hxx> +#include <TFunction_Logbook.hxx> + +//! Creation of an instance of the cut driver. It's possible (and recommended) +//! to have only one instance of a driver for the whole session. +class TOcafFunction_CutDriver : public TFunction_Driver +{ + DEFINE_STANDARD_RTTI_INLINE(TOcafFunction_CutDriver, TFunction_Driver) +public: + Standard_EXPORT static const Standard_GUID& GetID(); +public: + + TOcafFunction_CutDriver() {} + + //! Validation of the object label, its arguments and its results. + Standard_EXPORT virtual void Validate (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We call this method to check if the object was modified to be invoked. + //! If the object label or an argument is modified, we must recompute the object - to call the method Execute(). + Standard_EXPORT virtual Standard_Boolean MustExecute (const Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We compute the object and topologically name it. + //! If during the execution we found something wrong, we return the number of the failure. + //! For example: + //! 1 - an attribute hasn't been found, + //! 2 - algorithm failed, + //! if there are no any mistakes occurred we return 0: + //! 0 - no mistakes were found. + Standard_EXPORT virtual Standard_Integer Execute (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + +}; + +#endif diff --git a/samples/OCCTOverview/code/TOcafFunction_CylDriver.cxx b/samples/OCCTOverview/code/TOcafFunction_CylDriver.cxx new file mode 100644 index 0000000000..3b687e5172 --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_CylDriver.cxx @@ -0,0 +1,147 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TOcafFunction_CylDriver.h" + +#include <BRepPrimAPI_MakeCylinder.hxx> +#include <Standard_GUID.hxx> +#include <TCollection_AsciiString.hxx> +#include <TDF_Tool.hxx> +#include <TDataStd_Real.hxx> +#include <TNaming_Builder.hxx> + +//======================================================================= +//function : GetID +//purpose : +//======================================================================= +const Standard_GUID& TOcafFunction_CylDriver::GetID() +{ + static const Standard_GUID anID("22D22E53-D69A-11d4-8F1A-0060B0EE18E8"); + return anID; +} + +//======================================================================= +//function : TPartStd_CylDriver +//purpose : +//======================================================================= +TOcafFunction_CylDriver::TOcafFunction_CylDriver() +{ + // +} + +//======================================================================= +//function : Validate +//purpose : +//======================================================================= +void TOcafFunction_CylDriver::Validate (Handle(TFunction_Logbook)& log) const +{ + // We validate the object label ( Label() ), all the arguments and the results of the object: + log->SetValid(Label(), Standard_True); +} + +//======================================================================= +//function : MustExecute +//purpose : +//======================================================================= +Standard_Boolean TOcafFunction_CylDriver::MustExecute(const Handle(TFunction_Logbook)& log) const +{ + // If the object's label is modified: + if (log->IsModified(Label())) return Standard_True; + + // Cylinder (in our simple case) has 5 arguments: + // + // Let's check them: + if (log->IsModified(Label().FindChild(1))) + { + return Standard_True; // radius. + } + if (log->IsModified(Label().FindChild(2))) + { + return Standard_True; // height, + } + if (log->IsModified(Label().FindChild(3))) + { + return Standard_True; // x. + } + if (log->IsModified(Label().FindChild(4))) + { + return Standard_True; // y, + } + if (log->IsModified(Label().FindChild(5))) + { + return Standard_True; // z. + } + // if there are no any modifications concerned the Cyl, + // it's not necessary to recompute (to call the method Execute()): + return Standard_False; +} + +//======================================================================= +//function : Execute +//purpose : +//======================================================================= +Standard_Integer TOcafFunction_CylDriver::Execute(Handle(TFunction_Logbook)& /*log*/) const +{ + // Get the values of dimension and position attributes + Handle(TDataStd_Real) TSR; + Standard_Real x, y, z, r, h; + if (!Label().FindChild(1).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + r = TSR->Get(); + + if (!Label().FindChild(2).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + h = TSR->Get(); + + if (!Label().FindChild(3).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + x = TSR->Get(); + + if (!Label().FindChild(4).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + y = TSR->Get(); + + if (!Label().FindChild(5).FindAttribute(TDataStd_Real::GetID(), TSR)) + { + return 1; + } + z = TSR->Get(); + + // Build a Cyl using the dimension and position attributes + BRepPrimAPI_MakeCylinder mkCyl(gp_Ax2(gp_Pnt(x, y, z), gp_Dir(0, 0, 1)), r, h); + TopoDS_Shape ResultShape = mkCyl.Shape(); + + + // Build a TNaming_NamedShape using built Cyl + TNaming_Builder B(Label()); + B.Generated(ResultShape); + // That's all: + // If there are no any mistakes we return 0: + return 0; +} diff --git a/samples/OCCTOverview/code/TOcafFunction_CylDriver.h b/samples/OCCTOverview/code/TOcafFunction_CylDriver.h new file mode 100644 index 0000000000..e6d2534b71 --- /dev/null +++ b/samples/OCCTOverview/code/TOcafFunction_CylDriver.h @@ -0,0 +1,59 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _TOcafFunction_CylDriver_HeaderFile +#define _TOcafFunction_CylDriver_HeaderFile + +#include <TFunction_Driver.hxx> +#include <TFunction_Logbook.hxx> + +//! Creation of an instance of the cylinder driver. It's possible (and recommended) +//! to have only one instance of a driver for the whole session. +class TOcafFunction_CylDriver : public TFunction_Driver +{ + DEFINE_STANDARD_RTTI_INLINE(TOcafFunction_CylDriver, TFunction_Driver) +public: + Standard_EXPORT static const Standard_GUID& GetID(); +public: + + //! Creation of an instance of the driver. It's possible (and recommended) + //! to have only one instance of a driver for the whole session. + Standard_EXPORT TOcafFunction_CylDriver(); + + //! Validation of the object label, its arguments and its results. + Standard_EXPORT virtual void Validate (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We call this method to check if the object was modified to be invoked. + //! If the object label or an argument is modified, we must recompute the object - to call the method Execute(). + Standard_EXPORT virtual Standard_Boolean MustExecute (const Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + + //! We compute the object and topologically name it. + //! If during the execution we found something wrong, + //! we return the number of the failure. For example: + //! 1 - an attribute hasn't been found, + //! 2 - algorithm failed, + //! if there are no any mistakes occurred we return 0: + //! 0 - no mistakes were found. + Standard_EXPORT virtual Standard_Integer Execute (Handle(TFunction_Logbook)& theLog) const Standard_OVERRIDE; + +}; + +#endif diff --git a/samples/OCCTOverview/code/TOcaf_Application.cxx b/samples/OCCTOverview/code/TOcaf_Application.cxx new file mode 100644 index 0000000000..ceea5843f0 --- /dev/null +++ b/samples/OCCTOverview/code/TOcaf_Application.cxx @@ -0,0 +1,52 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TOcaf_Application.h" + +#include <TDF_Label.hxx> +#include <TFunction_DriverTable.hxx> +#include <TNaming_NamedShape.hxx> +#include <TPrsStd_AISPresentation.hxx> +#include <TPrsStd_AISViewer.hxx> + +#include "TOcafFunction_BoxDriver.h" +#include "TOcafFunction_CylDriver.h" +#include "TOcafFunction_CutDriver.h" + +//======================================================================= +//function : TOcaf_Application +//purpose : +//======================================================================= +TOcaf_Application::TOcaf_Application() +{ + // Instantiate a TOcafFunction_BoxDriver and add it to the TFunction_DriverTable + TFunction_DriverTable::Get()->AddDriver (TOcafFunction_BoxDriver::GetID(), + new TOcafFunction_BoxDriver()); + + // Instantiate a TOcafFunction_Cyl Driver and add it to the TFunction_DriverTable + TFunction_DriverTable::Get()->AddDriver (TOcafFunction_CylDriver::GetID(), + new TOcafFunction_CylDriver()); + + // Instantiate a TOcafFunction_CutDriver and add it to the TFunction_DriverTable + Handle(TOcafFunction_CutDriver) myCutDriver = new TOcafFunction_CutDriver(); + TFunction_DriverTable::Get()->AddDriver (TOcafFunction_CutDriver::GetID(), + new TOcafFunction_CutDriver()); +} diff --git a/samples/OCCTOverview/code/TOcaf_Application.h b/samples/OCCTOverview/code/TOcaf_Application.h new file mode 100644 index 0000000000..bcaaf03a06 --- /dev/null +++ b/samples/OCCTOverview/code/TOcaf_Application.h @@ -0,0 +1,37 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef _TOcaf_Application_HeaderFile +#define _TOcaf_Application_HeaderFile + +#include <TColStd_SequenceOfExtendedString.hxx> +#include <TDocStd_Application.hxx> + +//! Sample OCAF application +class TOcaf_Application : public TDocStd_Application +{ + DEFINE_STANDARD_RTTI_INLINE(TOcaf_Application, TDocStd_Application) +public: + + Standard_EXPORT TOcaf_Application(); +}; + +#endif diff --git a/samples/OCCTOverview/code/Topology.json b/samples/OCCTOverview/code/Topology.json new file mode 100644 index 0000000000..fb96cb4c2a --- /dev/null +++ b/samples/OCCTOverview/code/Topology.json @@ -0,0 +1,176 @@ +{ + "Topology": { + "Topological Shape": [{ + "text": "Vertex", + "function": "Vertex3dSample", + "description": "" + }, + { + "text": "Edge", + "function": "Edge3dSample", + "description": "" + }, + { + "text": "Face", + "function": "Face3dSample", + "description": "" + }, + { + "text": "Wire", + "function": "Wire3dSample", + "description": "" + }, + { + "text": "Shell", + "function": "Shell3dSample", + "description": "" + }, + { + "text": "Solid", + "function": "Solid3dSample", + "description": "" + }, + { + "text": "Edge (2D)", + "function": "Edge2dSample", + "description": "" + } + ], + "BRep primitive objects": [{ + "text": "Box", + "function": "Box3dSample", + "description": "" + }, + { + "text": "Cylinder", + "function": "Cylinder3dSample", + "description": "" + }, + { + "text": "Revolution", + "function": "Revolution3dSample", + "description": "" + } + ], + "Topology access": [{ + "text": "Topology iterator", + "function": "TopologyIterator3dSample", + "description": "" + }, + { + "text": "Topology explorer", + "function": "TopologyExplorer3dSample", + "description": "" + }, + { + "text": "Assess to curve", + "function": "AssessToCurve3dSample", + "description": "" + }, + { + "text": "Assess to composite curve", + "function": "AssessToCompositeCurve3dSample", + "description": "" + }, + { + "text": "Assess to surface", + "function": "AssessToSurface3dSample", + "description": "" + } + ], + "Boolean operation": [{ + "text": "Common", + "function": "Common3dSample", + "description": "" + }, + { + "text": "Cut", + "function": "Cut3dSample", + "description": "" + }, + { + "text": "Fuse", + "function": "Fuse3dSample", + "description": "" + }, + { + "text": "Section", + "function": "Section3dSample", + "description": "" + }, + { + "text": "Splitter", + "function": "Splitter3dSample", + "description": "" + }, + { + "text": "Defeaturing", + "function": "Defeaturing3dSample", + "description": "" + } + ], + "Complex modelling": [{ + "text": "Fillet", + "function": "Fillet3dSample", + "description": "" + }, + { + "text": "Chamfer", + "function": "Chamfer3dSample", + "description": "" + }, + { + "text": "Offset", + "function": "Offset3dSample", + "description": "" + }, + { + "text": "Evolved", + "function": "Evolved3dSample", + "description": "" + } + ], + "Modification": [{ + "text": "Copy", + "function": "Copy3dSample", + "description": "" + }, + { + "text": "Transform", + "function": "Transform3dSample", + "description": "" + }, + { + "text": "Convert to NURBS", + "function": "ConvertToNurbs3dSample", + "description": "" + }, + { + "text": "Sew contiguous faces", + "function": "SewContiguousFaces3dSample", + "description": "" + } + ], + "Calculation": [{ + "text": "Check validity", + "function": "CheckValidity3dSample", + "description": "" + }, + { + "text": "Compute linear properties", + "function": "ComputeLinearProperties3dSample", + "description": "" + }, + { + "text": "Compute surface properties", + "function": "ComputeSurfaceProperties3dSample", + "description": "" + }, + { + "text": "Compute volume properties", + "function": "ComputeVolumeProperties3dSample", + "description": "" + } + ] + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/TopologySamples.cxx b/samples/OCCTOverview/code/TopologySamples.cxx new file mode 100644 index 0000000000..17c4cc2dcc --- /dev/null +++ b/samples/OCCTOverview/code/TopologySamples.cxx @@ -0,0 +1,1884 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TopologySamples.h" + +#include "AdaptorVec_AIS.h" + +#include <gp_Circ.hxx> +#include <gp_Circ2d.hxx> +#include <gp_Cylinder.hxx> +#include <gp_Lin.hxx> +#include <gp_Pln.hxx> +#include <gp_Sphere.hxx> +#include <gp_Torus.hxx> + +#include <Geom_Axis1Placement.hxx> +#include <Geom_Axis2Placement.hxx> +#include <Geom_BSplineCurve.hxx> +#include <Geom2d_BSplineCurve.hxx> +#include <Geom_BSplineSurface.hxx> +#include <Geom_CartesianPoint.hxx> +#include <Geom_CylindricalSurface.hxx> +#include <Geom_Line.hxx> +#include <Geom_Plane.hxx> +#include <Geom_ToroidalSurface.hxx> +#include <GeomAPI_PointsToBSpline.hxx> +#include <Geom2dAPI_PointsToBSpline.hxx> +#include <GeomAPI_PointsToBSplineSurface.hxx> + +#include <TopoDS.hxx> +#include <TopoDS_Iterator.hxx> +#include <TopoDS_Compound.hxx> +#include <TopoDS_Edge.hxx> +#include <TopoDS_Face.hxx> +#include <TopoDS_Shell.hxx> +#include <TopoDS_Solid.hxx> +#include <TopoDS_Vertex.hxx> +#include <TopoDS_Wire.hxx> +#include <TopExp.hxx> +#include <TopExp_Explorer.hxx> + +#include <TColgp_Array2OfPnt.hxx> + +#include <BRep_Builder.hxx> +#include <BRepGProp.hxx> +#include <BRep_Tool.hxx> +#include <BRepTools.hxx> +#include <BRepTools_ReShape.hxx> +#include <BRepAdaptor_Curve.hxx> +#include <BRepAdaptor_CompCurve.hxx> +#include <BRepAdaptor_Surface.hxx> +#include <BRepAlgoAPI_Common.hxx> +#include <BRepAlgoAPI_Cut.hxx> +#include <BRepAlgoAPI_Fuse.hxx> +#include <BRepAlgoAPI_Section.hxx> +#include <BRepAlgoAPI_Splitter.hxx> +#include <BRepAlgoAPI_Defeaturing.hxx> +#include <BRepBuilderAPI_Copy.hxx> +#include <BRepBuilderAPI_MakeVertex.hxx> +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <BRepBuilderAPI_MakeEdge2d.hxx> +#include <BRepBuilderAPI_MakeFace.hxx> +#include <BRepBuilderAPI_MakePolygon.hxx> +#include <BRepBuilderAPI_MakeShell.hxx> +#include <BRepBuilderAPI_MakeSolid.hxx> +#include <BRepBuilderAPI_MakeWire.hxx> +#include <BRepBuilderAPI_NurbsConvert.hxx> +#include <BRepBuilderAPI_Sewing.hxx> +#include <BRepBuilderAPI_Transform.hxx> +#include <BRepCheck_Analyzer.hxx> +#include <BRepPrimAPI_MakeBox.hxx> +#include <BRepPrimAPI_MakeCylinder.hxx> +#include <BRepPrimAPI_MakeRevol.hxx> +#include <BRepFilletAPI_MakeChamfer.hxx> +#include <BRepFilletAPI_MakeFillet.hxx> +#include <BRepOffsetAPI_MakeOffset.hxx> +#include <BRepOffsetAPI_MakeEvolved.hxx> +#include <Extrema_ExtCS.hxx> +#include <GCPnts_QuasiUniformDeflection.hxx> +#include <GProp_GProps.hxx> +#include <GProp_PrincipalProps.hxx> + +#include <AIS_Axis.hxx> +#include <AIS_ColoredShape.hxx> +#include <AIS_Plane.hxx> +#include <AIS_Point.hxx> +#include <AIS_TextLabel.hxx> + +void TopologySamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "Vertex3dSample") + Vertex3dSample(); + else if (theSampleName == "Edge3dSample") + Edge3dSample(); + else if (theSampleName == "Face3dSample") + Face3dSample(); + else if (theSampleName == "Wire3dSample") + Wire3dSample(); + else if (theSampleName == "Shell3dSample") + Shell3dSample(); + else if (theSampleName == "Solid3dSample") + Solid3dSample(); + else if (theSampleName == "Edge2dSample") + Edge2dSample(); + else if (theSampleName == "Box3dSample") + Box3dSample(); + else if (theSampleName == "Cylinder3dSample") + Cylinder3dSample(); + else if (theSampleName == "Revolution3dSample") + Revolution3dSample(); + else if (theSampleName == "TopologyIterator3dSample") + TopologyIterator3dSample(); + else if (theSampleName == "TopologyExplorer3dSample") + TopologyExplorer3dSample(); + else if (theSampleName == "AssessToCurve3dSample") + AssessToCurve3dSample(); + else if (theSampleName == "AssessToCompositeCurve3dSample") + AssessToCompositeCurve3dSample(); + else if (theSampleName == "AssessToSurface3dSample") + AssessToSurface3dSample(); + else if (theSampleName == "Common3dSample") + Common3dSample(); + else if (theSampleName == "Cut3dSample") + Cut3dSample(); + else if (theSampleName == "Cut3dSample") + Cut3dSample(); + else if (theSampleName == "Fuse3dSample") + Fuse3dSample(); + else if (theSampleName == "Section3dSample") + Section3dSample(); + else if (theSampleName == "Splitter3dSample") + Splitter3dSample(); + else if (theSampleName == "Defeaturing3dSample") + Defeaturing3dSample(); + else if (theSampleName == "Fillet3dSample") + Fillet3dSample(); + else if (theSampleName == "Chamfer3dSample") + Chamfer3dSample(); + else if (theSampleName == "Offset3dSample") + Offset3dSample(); + else if (theSampleName == "Evolved3dSample") + Evolved3dSample(); + else if (theSampleName == "Copy3dSample") + Copy3dSample(); + else if (theSampleName == "Transform3dSample") + Transform3dSample(); + else if (theSampleName == "ConvertToNurbs3dSample") + ConvertToNurbs3dSample(); + else if (theSampleName == "SewContiguousFaces3dSample") + SewContiguousFaces3dSample(); + else if (theSampleName == "CheckValidity3dSample") + CheckValidity3dSample(); + else if (theSampleName == "ComputeLinearProperties3dSample") + ComputeLinearProperties3dSample(); + else if (theSampleName == "ComputeSurfaceProperties3dSample") + ComputeSurfaceProperties3dSample(); + else if (theSampleName == "ComputeVolumeProperties3dSample") + ComputeVolumeProperties3dSample(); + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void TopologySamples::Vertex3dSample() +{ + // Make a vertex from a 3D point. + gp_Pnt aPnt(0.0, 0.0, 10.0); + TopoDS_Vertex aVertex = BRepBuilderAPI_MakeVertex(aPnt); + myResult << "TopoDS_Vertex was created at [ " + << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() + << " ]" << std::endl; + + Handle(AIS_Shape) aAisVertex = new AIS_Shape(aVertex); + Handle(AIS_TextLabel) anAisLabel = new AIS_TextLabel(); + Standard_SStream aSS; + aSS << "TopoDS_Vertex [" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << "]" << std::endl; + anAisLabel->SetText(aSS.str().c_str()); + anAisLabel->SetPosition(aPnt); + myObject3d.Append(aAisVertex); + myObject3d.Append(anAisLabel); +} + +void TopologySamples::Edge3dSample() +{ + // Make an edge from two 3D points. + gp_Pnt aPnt1(0.0, 10.0, 0.0); + gp_Pnt aPnt2(10.0, 10.0, 0.0); + TopoDS_Edge anEdgeP12 = BRepBuilderAPI_MakeEdge(aPnt1, aPnt2); + myResult << "TopoDS_Edge between [ " + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << " ] and [ " + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << " ] was created in yellow" << std::endl + << std::endl; + + // Make an edge from a circular segment. + // Create a circle in XY plane of the radius 5.0. + gp_Circ aCirc(gp::XOY(), 5.0); + // Make a circular edge from the 1st quoter in the parametric space. + TopoDS_Edge anEdgeCirc = BRepBuilderAPI_MakeEdge(aCirc, 0.0, M_PI_2); + myResult << "TopoDS_Edge on the circle's 1st quoter" << std::endl + << "with the center at [ " + << aCirc.Location().X() << ", " << aCirc.Location().Y() << ", " << aCirc.Location().Z() + << " ] and R = " << aCirc.Radius() << " was created in red" << std::endl + << std::endl; + + // Make an edge from a 3D curve (BSpline). + // Define points. + gp_Pnt aPole1(0.0, 0.0, 10.0); + gp_Pnt aPole2(5.0, 5.0, 5.0); + gp_Pnt aPole3(10.0, 10.0, 15.0); + gp_Pnt aPole4(15.0, 5.0, 20.0); + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoles(1, 4); + aPoles.SetValue(1, aPole1); + aPoles.SetValue(2, aPole2); + aPoles.SetValue(3, aPole3); + aPoles.SetValue(4, aPole4); + // Make a BSpline curve from the points array + Handle(Geom_BSplineCurve) aBSplineCurve = GeomAPI_PointsToBSpline(aPoles).Curve(); + // Make an edge between two point on the BSpline curve. + gp_Pnt aPntOnCurve1, aPntOnCurve2; + aBSplineCurve->D0 (0.75 * aBSplineCurve->FirstParameter() + + 0.25 * aBSplineCurve->LastParameter(), + aPntOnCurve1); + aBSplineCurve->D0 (0.25 * aBSplineCurve->FirstParameter() + + 0.75 * aBSplineCurve->LastParameter(), + aPntOnCurve2); + TopoDS_Edge anEdgeBSpline = BRepBuilderAPI_MakeEdge(aBSplineCurve, aPntOnCurve1, aPntOnCurve2); + myResult << "TopoDS_Edge on the BSpline curve" << std::endl + << "between [ " + << aPntOnCurve1.X() << ", " << aPntOnCurve1.Y() << ", " << aPntOnCurve1.Z() + << " ] and [ " + << aPntOnCurve2.X() << ", " << aPntOnCurve2.Y() << ", " << aPntOnCurve2.Z() + << " ]" << std::endl + << "was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisEdgeP12 = new AIS_ColoredShape(anEdgeP12); + Handle(AIS_ColoredShape) anAisEdgeCirc = new AIS_ColoredShape(anEdgeCirc); + Handle(AIS_ColoredShape) anAisEdgeBSpline = new AIS_ColoredShape(anEdgeBSpline); + anAisEdgeP12->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEdgeCirc->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisEdgeBSpline->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisEdgeP12); + myObject3d.Append(anAisEdgeCirc); + myObject3d.Append(anAisEdgeBSpline); + Handle(AIS_TextLabel) anAisEdgeP12Label = new AIS_TextLabel(); + anAisEdgeP12Label->SetText("Edge between two points"); + anAisEdgeP12Label->SetPosition(0.5 * (aPnt1.XYZ() + aPnt2.XYZ())); + anAisEdgeP12Label->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisEdgeP12Label); + Handle(AIS_TextLabel) anAisEdgeCircLabel = new AIS_TextLabel(); + anAisEdgeCircLabel->SetText("Circular edge"); + anAisEdgeCircLabel->SetPosition(aCirc.Location()); + anAisEdgeCircLabel->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisEdgeCircLabel); + Handle(AIS_TextLabel) anAisEdgeBSplineLabel = new AIS_TextLabel(); + anAisEdgeBSplineLabel->SetText("BSpline edge"); + anAisEdgeBSplineLabel->SetPosition(aPole3); + anAisEdgeBSplineLabel->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisEdgeBSplineLabel); + TopoDS_Vertex anEdgeP12_V1, anEdgeP12_V2; + TopExp::Vertices(anEdgeP12, anEdgeP12_V1, anEdgeP12_V2); + myObject3d.Append(new AIS_Shape(anEdgeP12_V1)); + myObject3d.Append(new AIS_Shape(anEdgeP12_V2)); + TopoDS_Vertex anEdgeCirc_V1, anEdgeCirc_V2; + TopExp::Vertices(anEdgeCirc, anEdgeCirc_V1, anEdgeCirc_V2); + myObject3d.Append(new AIS_Shape(anEdgeCirc_V1)); + myObject3d.Append(new AIS_Shape(anEdgeCirc_V2)); + TopoDS_Vertex anEdgeBSpline_V1, anEdgeBSpline_V2; + TopExp::Vertices(anEdgeBSpline, anEdgeBSpline_V1, anEdgeBSpline_V2); + myObject3d.Append(new AIS_Shape(anEdgeBSpline_V1)); + myObject3d.Append(new AIS_Shape(anEdgeBSpline_V2)); +} + +void TopologySamples::Face3dSample() +{ + // Make a face from a sphere with the center + // at [0.0, 0.0, 10.0] and R = 5. + gp_Sphere aSphere(gp_Ax3(gp_Pnt(0.0, 0.0, 10.0), gp::DZ()), 5.0); + TopoDS_Face aFaceSphere = BRepBuilderAPI_MakeFace(aSphere); + myResult << "TopoDS_Face on the sphere with" << std::endl + << "the center at [ " + << aSphere.Location().X() << ", " << aSphere.Location().Y() << ", " << aSphere.Location().Z() + << " ] and R = " << aSphere.Radius() << " was created in yellow" << std::endl + << std::endl; + + // Make a flat rectangular face on XY plane. + gp_Pln aPln(gp::XOY()); + TopoDS_Face aFaceRect = BRepBuilderAPI_MakeFace(aPln, -10.0, +10.0, -20.0, +20.0); + myResult << "TopoDS_Face on the rectangle was created in red" << std::endl + << std::endl; + + // Make a face from a BSpline surface. + // Define a 4x4 grid of points for BSpline surface. + TColgp_Array2OfPnt aPoints(1, 4, 1, 4); + for (Standard_Integer i = 1; i <= 4; ++i) + { + gp_Pnt aPnt; + aPnt.SetX(5.0 * i); + for (Standard_Integer j = 1; j <= 4; ++j) + { + aPnt.SetY(5.0 * j); + if (1 < i && i < 4 && 1 < j && j < 4) + { + aPnt.SetZ(15.0); + } + else + { + aPnt.SetZ(10.0); + } + aPoints.SetValue(i, j, aPnt); + } + } + // Make a BSpline surface from the points array. + Handle(Geom_BSplineSurface) aBSplineSurf = GeomAPI_PointsToBSplineSurface(aPoints).Surface(); + Standard_Real aU1, aU2, aV1, aV2; + aBSplineSurf->Bounds(aU1, aU2, aV1, aV2); + TopoDS_Face aFaceBSpline = BRepBuilderAPI_MakeFace(aBSplineSurf, aU1, aU2, aV1, aV2, Precision::Confusion()); + myResult << "TopoDS_Face on the BSpline surface was created in green" << std::endl << std::endl; + + Handle(AIS_ColoredShape) anAisFaceSphere = new AIS_ColoredShape(aFaceSphere); + Handle(AIS_ColoredShape) anAisFaceRect = new AIS_ColoredShape(aFaceRect); + Handle(AIS_ColoredShape) anAisFaceBSpline = new AIS_ColoredShape(aFaceBSpline); + anAisFaceSphere->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisFaceRect->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisFaceBSpline->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisFaceSphere); + myObject3d.Append(anAisFaceRect); + myObject3d.Append(anAisFaceBSpline); + Handle(AIS_TextLabel) anAisFaceSphereLabel = new AIS_TextLabel(); + anAisFaceSphereLabel->SetText("Spherical face"); + anAisFaceSphereLabel->SetPosition(aSphere.Location().XYZ() + aSphere.Radius() * gp::DZ().XYZ()); + anAisFaceSphereLabel->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisFaceSphereLabel); + Handle(AIS_TextLabel) anAisFaceRectLabel = new AIS_TextLabel(); + anAisFaceRectLabel->SetText("Flat rectangular face"); + anAisFaceRectLabel->SetPosition(aPln.Location().XYZ() + 2.5 * gp::DZ().XYZ()); + anAisFaceRectLabel->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisFaceRectLabel); + Handle(AIS_TextLabel) anAisFaceBSplineLabel = new AIS_TextLabel(); + anAisFaceBSplineLabel->SetText("BSpline face"); + anAisFaceBSplineLabel->SetPosition(aPoints(4, 4)); + anAisFaceBSplineLabel->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisFaceBSplineLabel); +} + +void TopologySamples::Wire3dSample() +{ + // Make a wire from edges created on a set of points. + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoints(1, 4); + aPoints.SetValue(1, gp_Pnt(0.0, 0.0, 0.0)); + aPoints.SetValue(2, gp_Pnt(20.0, 0.0, 0.0)); + aPoints.SetValue(3, gp_Pnt(20.0, 10.0, 0.0)); + aPoints.SetValue(4, gp_Pnt(0.0, 10.0, 0.0)); + // A wire maker contains an empty wire. + BRepBuilderAPI_MakeWire aMakeWire; + for (Standard_Integer i = 1; i <= 4; ++i) + { + Standard_Integer i1 = i; + Standard_Integer i2 = i1 < 4 ? i1 + 1 : 1; + const gp_Pnt& aPnt1 = aPoints.Value(i1); + const gp_Pnt& aPnt2 = aPoints.Value(i2); + TopoDS_Edge anEdge = BRepBuilderAPI_MakeEdge(aPnt1, aPnt2); + // Add an edge to the wire under construction. + // The edge must be connectible to the wire under construction, and, + // unless it is the first edge of the wire, must satisfy the following + // condition: one of its vertices must be geometrically coincident + // with one of the vertices of the wire (provided that the highest + // tolerance factor is assigned to the two vertices). + // It could also be the same vertex. + // Warning + // If the edge is not connectible to the wire under construction it is not added. + // The function IsDone will return false and the function + // Wire will raise an error, until a new connectible edge is added. + aMakeWire.Add(anEdge); + Standard_ASSERT_VOID(aMakeWire.IsDone(), "Added edge isn't connectible!"); + } + // Retrieve a constructed wire. + TopoDS_Wire aWire = aMakeWire.Wire(); + myResult << "TopoDS_Wire was created. Vertices :" << std::endl; + // Retrieve wire vertices. 4 vertices are expected, because of + // edges connecting during wire constructing. + TopTools_IndexedMapOfShape aVertices; + TopExp::MapShapes(aWire, TopAbs_VERTEX, aVertices); + for (TopTools_IndexedMapOfShape::Iterator anIt(aVertices); anIt.More(); anIt.Next()) + { + TopoDS_Vertex aVertex = TopoDS::Vertex(anIt.Value()); + gp_Pnt aPnt = BRep_Tool::Pnt(aVertex); + myResult << "[ " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << " ]" << std::endl; + Handle(AIS_Shape) anAisVertex = new AIS_Shape(aVertex); + myObject3d.Append(anAisVertex); + } + + Handle(AIS_Shape) anAisWire = new AIS_Shape(aWire); + myObject3d.Append(anAisWire); +} + +void TopologySamples::Shell3dSample() +{ + // Make a shell from a cylinder with R = 5 and directed along Z axis + gp_Cylinder aCyl(gp::XOY(), 5.0); + Handle(Geom_Surface) aCylSurf = new Geom_CylindricalSurface(aCyl); + TopoDS_Shell aCylShell = BRepBuilderAPI_MakeShell(aCylSurf, 0.0, 2.0 * M_PI, -10.0, +10.0); + myResult << "TopoDS_Shell on the cylinder R = " << aCyl.Radius() << std::endl + << "with axis [ " + << aCyl.Position().Direction().X() << ", " + << aCyl.Position().Direction().Y() << ", " + << aCyl.Position().Direction().Z() << " ]" << std::endl + << "limited in length [-10 ... +10] was created" << std::endl; + + Handle(AIS_Shape) anAisShell = new AIS_Shape(aCylShell); + myObject3d.Append(anAisShell); +} + +void TopologySamples::Solid3dSample() +{ + // Make a torus from a shell. + gp_Torus aTorus(gp::XOY(), 20.0, 7.5); + Handle(Geom_Surface) aTorusSurf = new Geom_ToroidalSurface(aTorus); + TopoDS_Shell aTorusShell = BRepBuilderAPI_MakeShell(aTorusSurf, 0.0, 2.0 * M_PI, 0.0, 2.0 * M_PI); + // Make a solid on the torus shell. + TopoDS_Solid aTorusSolid = BRepBuilderAPI_MakeSolid(aTorusShell); + myResult << "TopoDS_Solid on the torus with" << std::endl + << "R major = " << aTorus.MajorRadius() << std::endl + << "R minor = " << aTorus.MinorRadius() << std::endl + << "was created" << std::endl; + + Handle(AIS_Shape) anAisSolid = new AIS_Shape(aTorusSolid); + myObject3d.Append(anAisSolid); +} + +void TopologySamples::Edge2dSample() +{ + // Make an edge from two 2D points. + gp_Pnt2d aPnt1(0.0, 10.0); + gp_Pnt2d aPnt2(10.0, 10.0); + TopoDS_Edge anEdgeP12 = BRepBuilderAPI_MakeEdge2d(aPnt1, aPnt2); + myResult << "TopoDS_Edge between [ " + << aPnt1.X() << ", " << aPnt1.Y() << " ] and [ " + << aPnt2.X() << ", " << aPnt2.Y() << " ] was created in yellow" << std::endl + << std::endl; + + // Make an edge from a circular segment. + // Create a circle of the radius 5.0. + gp_Circ2d aCirc(gp::OX2d(), 5.0); + // Make a circular edge from the 1st quoter in the parametric space. + TopoDS_Edge anEdgeCirc = BRepBuilderAPI_MakeEdge2d(aCirc, 0.0, M_PI_2); + myResult << "TopoDS_Edge on the 2D circle's 1st quoter" << std::endl + << "with the center at [ " << aCirc.Location().X() << ", " << aCirc.Location().Y() + << " ] and R = " << aCirc.Radius() << " was created in red" << std::endl + << std::endl; + + // Make an edge from a 2D curve (BSpline). + // Define points. + gp_Pnt2d aPole1(0.0, 0.0); + gp_Pnt2d aPole2(5.0, 5.0); + gp_Pnt2d aPole3(10.0, 10.0); + gp_Pnt2d aPole4(15.0, 5.0); + // Add points to the curve poles array. + TColgp_Array1OfPnt2d aPoles(1, 4); + aPoles.SetValue(1, aPole1); + aPoles.SetValue(2, aPole2); + aPoles.SetValue(3, aPole3); + aPoles.SetValue(4, aPole4); + // Make a BSpline curve from the points array + Handle(Geom2d_BSplineCurve) aBSplineCurve = Geom2dAPI_PointsToBSpline(aPoles).Curve(); + // Make an edge between two point on the BSpline curve. + gp_Pnt2d aPntOnCurve1, aPntOnCurve2; + aBSplineCurve->D0 (0.75 * aBSplineCurve->FirstParameter() + + 0.25 * aBSplineCurve->LastParameter(), + aPntOnCurve1); + aBSplineCurve->D0 (0.25 * aBSplineCurve->FirstParameter() + + 0.75 * aBSplineCurve->LastParameter(), + aPntOnCurve2); + TopoDS_Edge anEdgeBSpline = BRepBuilderAPI_MakeEdge2d(aBSplineCurve, aPntOnCurve1, aPntOnCurve2); + myResult << "TopoDS_Edge on the 2D BSpline curve" << std::endl + << "between [ " << aPntOnCurve1.X() << ", " << aPntOnCurve1.Y() + << " ] and [ " << aPntOnCurve2.X() << ", " << aPntOnCurve2.Y() << " ]" << std::endl + << "was created in green" << std::endl; + + Handle(AIS_ColoredShape) anAisEdgeP12 = new AIS_ColoredShape(anEdgeP12); + Handle(AIS_ColoredShape) anAisEdgeCirc = new AIS_ColoredShape(anEdgeCirc); + Handle(AIS_ColoredShape) anAisEdgeBSpline = new AIS_ColoredShape(anEdgeBSpline); + anAisEdgeP12->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEdgeCirc->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisEdgeBSpline->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject2d.Append(anAisEdgeP12); + myObject2d.Append(anAisEdgeCirc); + myObject2d.Append(anAisEdgeBSpline); + Handle(AIS_TextLabel) anAisEdgeP12Label = new AIS_TextLabel(); + anAisEdgeP12Label->SetText("Edge between two 2d points"); + anAisEdgeP12Label->SetPosition(0.5 * (gp_XYZ(aPnt1.X(), aPnt1.Y() + 0.5, 0.0) + gp_XYZ(aPnt2.X(), aPnt2.Y() + 0.5, 0.0))); + anAisEdgeP12Label->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject2d.Append(anAisEdgeP12Label); + Handle(AIS_TextLabel) anAisEdgeCircLabel = new AIS_TextLabel(); + anAisEdgeCircLabel->SetText("Circular edge"); + anAisEdgeCircLabel->SetPosition(gp_XYZ(aCirc.Location().X(), aCirc.Location().Y() + 0.5, 0.0)); + anAisEdgeCircLabel->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject2d.Append(anAisEdgeCircLabel); + Handle(AIS_TextLabel) anAisEdgeBSplineLabel = new AIS_TextLabel(); + anAisEdgeBSplineLabel->SetText("BSpline edge"); + anAisEdgeBSplineLabel->SetPosition(gp_XYZ(aPole3.X(), aPole3.Y() + 0.5, 0.0)); + anAisEdgeBSplineLabel->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject2d.Append(anAisEdgeBSplineLabel); + TopoDS_Vertex anEdgeP12_V1, anEdgeP12_V2; + TopExp::Vertices(anEdgeP12, anEdgeP12_V1, anEdgeP12_V2); + myObject2d.Append(new AIS_Shape(anEdgeP12_V1)); + myObject2d.Append(new AIS_Shape(anEdgeP12_V2)); + TopoDS_Vertex anEdgeCirc_V1, anEdgeCirc_V2; + TopExp::Vertices(anEdgeCirc, anEdgeCirc_V1, anEdgeCirc_V2); + myObject2d.Append(new AIS_Shape(anEdgeCirc_V1)); + myObject2d.Append(new AIS_Shape(anEdgeCirc_V2)); + TopoDS_Vertex anEdgeBSpline_V1, anEdgeBSpline_V2; + TopExp::Vertices(anEdgeBSpline, anEdgeBSpline_V1, anEdgeBSpline_V2); + myObject2d.Append(new AIS_Shape(anEdgeBSpline_V1)); + myObject2d.Append(new AIS_Shape(anEdgeBSpline_V2)); +} + +void TopologySamples::Box3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 5.0; + Standard_Real aSizeY = 10.0; + Standard_Real aSizeZ = 15.0; + TopoDS_Shape aBox1 = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow" << std::endl; + + // Make a box by two points. + gp_Pnt aPnt1(10.0, 0.0, 0.0); + gp_Pnt aPnt2(20.0, 10.0, 15.0); + TopoDS_Shape aBox2 = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in red" << std::endl; + + Handle(AIS_ColoredShape) anAisBox1 = new AIS_ColoredShape(aBox1); + Handle(AIS_ColoredShape) anAisBox2 = new AIS_ColoredShape(aBox2); + anAisBox1->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisBox2->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBox1); + myObject3d.Append(anAisBox2); +} + +void TopologySamples::Cylinder3dSample() +{ + // Make a cylinder of the specified radius and length. + Standard_Real aRadius1 = 5.0; + Standard_Real aLength1 = 15.0; + TopoDS_Shape aCyl1 = BRepPrimAPI_MakeCylinder(aRadius1, aLength1); + myResult << "Cylinder with Radius = " << aRadius1 + << " and Length = " << aLength1 + << " was created in yellow" << std::endl; + + // Make a cylinder of the specified radius, length and sector angle. + Standard_Real aRadius2 = 8.0; + Standard_Real aLength2 = 25.0; + Standard_Real anAngle = M_PI_2; + TopoDS_Shape aCyl2 = BRepPrimAPI_MakeCylinder(aRadius2, aLength2, anAngle); + myResult << "Cylinder with Radius = " << aRadius2 + << " , Length = " << aLength2 + << " and Angle = " << anAngle + << " was created in red" << std::endl; + + Handle(AIS_ColoredShape) anAisCyl1 = new AIS_ColoredShape(aCyl1); + Handle(AIS_ColoredShape) anAisCyl2 = new AIS_ColoredShape(aCyl2); + anAisCyl1->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisCyl2->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisCyl1); + myObject3d.Append(anAisCyl2); +} + +void TopologySamples::Revolution3dSample() +{ + // Make a toroidal face by a series of shape revolves. + // Make a starting vertex at [-1.0, 0, 0]. + TopoDS_Shape aVertex = BRepBuilderAPI_MakeVertex(gp_Pnt(-1.0, 0.0, 0.0)); + + // Make a circular edge by revolting aVertex around + // an axis Y positioned at [-1.5, 0.0, 0.0] on 2*Pi angle + gp_Ax1 anAxis1(gp_Pnt(-1.5, 0.0, 0.0), gp::DY()); + TopoDS_Shape anEdge = BRepPrimAPI_MakeRevol(aVertex, anAxis1); + myResult << "Circular edge was created in yellow" << std::endl; + + // Make a toroidal face by revolting anEdge around + // Z axis on 2*Pi angle. + TopoDS_Shape aFace = BRepPrimAPI_MakeRevol(anEdge, gp::OZ()); + myResult << "Toroidal face was created in red" << std::endl; + + Handle(AIS_Axis) anAisAxis1 = new AIS_Axis(new Geom_Axis1Placement(anAxis1)); + Handle(AIS_Axis) anAisAxis2 = new AIS_Axis(new Geom_Axis1Placement(gp::OZ())); + Handle(AIS_Shape) anAisVertex = new AIS_Shape(aVertex); + Handle(AIS_ColoredShape) anAisEdge = new AIS_ColoredShape(anEdge); + Handle(AIS_ColoredShape) anAisFace = new AIS_ColoredShape(aFace); + anAisEdge->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisEdge->SetWidth(1.5); + anAisAxis1->SetColor(Quantity_NOC_GREEN); + anAisFace->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisAxis2->SetColor(Quantity_NOC_RED); + myObject3d.Append(anAisVertex); + myObject3d.Append(anAisEdge); + myObject3d.Append(anAisFace); +} + +void TopologySamples::TopologyIterator3dSample() +{ + // Make a compound shape. + TopoDS_Compound aComp; + BRep_Builder aBuilder; + aBuilder.MakeCompound(aComp); + // Add shapes to the compound. + aBuilder.Add(aComp, BRepBuilderAPI_MakeVertex(gp::Origin())); + aBuilder.Add(aComp, BRepBuilderAPI_MakeEdge(gp_Pnt(5.0, 0.0, 0.0), gp_Pnt(10.0, 0.0, 0.0))); + aBuilder.Add(aComp, BRepBuilderAPI_MakeFace(gp_Sphere(gp::XOY(), 10.0))); + aBuilder.Add(aComp, BRepBuilderAPI_MakeWire( + BRepBuilderAPI_MakeEdge(gp_Pnt(15.0, 0.0, 0.0), gp_Pnt(20.0, 0.0, 0.0)), + BRepBuilderAPI_MakeEdge(gp_Pnt(20.0, 0.0, 0.0), gp_Pnt(25.0, 10.0, 5.0)) + )); + aBuilder.Add(aComp, BRepPrimAPI_MakeBox(5.0, 6.0, 7.0).Shell()); + aBuilder.Add(aComp, BRepPrimAPI_MakeBox(5.0, 6.0, 7.0).Solid()); + TopoDS_Compound aComp1; + aBuilder.MakeCompound(aComp1); + aBuilder.Add(aComp, aComp1); + + // Iterate over compound components. + myResult << "Compound components:" << std::endl; + Standard_Integer anI = 1; + for (TopoDS_Iterator anIt(aComp); anIt.More(); anIt.Next(), ++anI) + { + const TopoDS_Shape& aShape = anIt.Value(); + myResult << "#" << anI << " : "; + Handle(AIS_ColoredShape) anAisShape; + switch (aShape.ShapeType()) + { + case TopAbs_VERTEX: + myResult << "TopAbs_VERTEX"; + anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + break; + case TopAbs_EDGE: + anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myResult << "TopAbs_EDGE"; + break; + case TopAbs_WIRE: + myResult << "TopAbs_WIRE"; + break; + case TopAbs_FACE: + anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_RED)); + myResult << "TopAbs_FACE"; + break; + case TopAbs_SHELL: + myResult << "TopAbs_SHELL"; + break; + case TopAbs_SOLID: + myResult << "TopAbs_SOLID"; + break; + case TopAbs_COMPOUND: + myResult << "TopAbs_COMPOUND"; + break; + case TopAbs_COMPSOLID: + myResult << "TopAbs_COMPSOLID"; + break; + case TopAbs_SHAPE: + myResult << "TopAbs_SHAPE"; + break; + } + myResult << std::endl; + if (anAisShape) + { + myObject3d.Append(anAisShape); + } + } +} + +void TopologySamples::TopologyExplorer3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 5.0; + Standard_Real aSizeY = 10.0; + Standard_Real aSizeZ = 15.0; + TopoDS_Shape aBox = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + + // Explore vertex references. + myResult << "Vertex refs. : "; + Standard_Integer nbVertices = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_VERTEX); anExp.More(); anExp.Next(), ++nbVertices) + { + const TopoDS_Shape& aShape = anExp.Current(); + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisShape); + } + myResult << nbVertices << std::endl; + + // Explore edge references. + myResult << "Edge refs. : "; + Standard_Integer nbEdges = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_EDGE); anExp.More(); anExp.Next(), ++nbEdges) + { + const TopoDS_Shape& aShape = anExp.Current(); + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisShape->SetWidth(2.5); + myObject3d.Append(anAisShape); + } + myResult << nbEdges << std::endl; + + // Explore face references. + myResult << "Face refs. : "; + Standard_Integer nbFaces = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_FACE); anExp.More(); anExp.Next(), ++nbFaces) + { + const TopoDS_Shape& aShape = anExp.Current(); + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisShape->SetWidth(2.5); + myObject3d.Append(anAisShape); + } + myResult << nbFaces << std::endl; + + // Explore shell references. + myResult << "Wire refs. : "; + Standard_Integer nbWires = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_WIRE); anExp.More(); anExp.Next(), ++nbWires) + { + } + myResult << nbWires << std::endl; + + // Explore shell references. + myResult << "Shell refs. : "; + Standard_Integer nbShells = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_SHELL); anExp.More(); anExp.Next(), ++nbShells) + { + } + myResult << nbShells << std::endl; + + // Explore solid references. + myResult << "Solid refs. : "; + Standard_Integer nbSolids = 0; + for (TopExp_Explorer anExp(aBox, TopAbs_SOLID); anExp.More(); anExp.Next(), ++nbSolids) + { + } + myResult << nbSolids << std::endl; +} + +void TopologySamples::AssessToCurve3dSample() +{ + // Make a face from a sphere. + gp_Sphere aSphere(gp::XOY(), 1.0); + TopoDS_Face aFace = BRepBuilderAPI_MakeFace(aSphere); + myResult << "TopoDS_Face on the sphere with" << std::endl + << "the center at [ " + << aSphere.Location().X() << ", " << aSphere.Location().Y() << ", " << aSphere.Location().Z() + << " ] and R = " << aSphere.Radius() << " was created in yellow" << std::endl + << std::endl; + + Handle(AIS_ColoredShape) anAisFace = new AIS_ColoredShape(aFace); + anAisFace->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisFace); + + // Retrieve the first not degenerated edge. + TopoDS_Edge aCurveEdge; + for (TopExp_Explorer anExp(aFace, TopAbs_EDGE); anExp.More(); anExp.Next()) + { + TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current()); + if (!BRep_Tool::Degenerated(anEdge)) + { + aCurveEdge = anEdge; + break; + } + } + if (!aCurveEdge.IsNull()) + { + // Make a curve on edge adaptor. + BRepAdaptor_Curve aCurveAdaptor(aCurveEdge); + myResult << "Curve adaptor for edge was built in red" << std::endl; + + Handle(AIS_ColoredShape) anAisCurveEdge = new AIS_ColoredShape(aCurveEdge); + anAisCurveEdge->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisCurveEdge->SetWidth(1.5); + myObject3d.Append(anAisCurveEdge); + + // Use the curve adaptor for some calculations, e.g. compute + // a set of points using GCPnts_QuasiUniformDeflection algo. + Standard_Real aDeflection = 0.1; + GCPnts_QuasiUniformDeflection anAlgo(aCurveAdaptor, aDeflection); + Standard_ASSERT_VOID(anAlgo.IsDone(), "Success is expected!"); + myResult << "Distribution of point on the curve with " << aDeflection + << " deflection was performed:" << std::endl; + for (Standard_Integer i = 1; i <= anAlgo.NbPoints(); ++i) + { + gp_Pnt aPnt = anAlgo.Value(i); + myResult << "Point #" << i << " : [ " + << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << " ]" << std::endl; + Handle(AIS_Point) anAisPnt = new AIS_Point(new Geom_CartesianPoint(aPnt)); + myObject3d.Append(anAisPnt); + } + } +} + +void TopologySamples::AssessToCompositeCurve3dSample() +{ + // Make a wire containing two BSpline curves. + // Define points. + gp_Pnt aPole1(0.0, 0.0, 10.0); + gp_Pnt aPole2(5.0, 5.0, 5.0); + gp_Pnt aPole3(10.0, 10.0, 15.0); + gp_Pnt aPole4(15.0, 5.0, 20.0); + gp_Pnt aPole5(25.0, 15.0, 20.0); + gp_Pnt aPole6(35.0, 15.0, 15.0); + gp_Pnt aPole7(45.0, 25.0, 10.0); + // Add points to the curve poles array. + TColgp_Array1OfPnt aPoles1(1, 4), aPoles2(1, 4); + aPoles1.SetValue(1, aPole1); + aPoles1.SetValue(2, aPole2); + aPoles1.SetValue(3, aPole3); + aPoles1.SetValue(4, aPole4); + aPoles2.SetValue(1, aPole4); + aPoles2.SetValue(2, aPole5); + aPoles2.SetValue(3, aPole6); + aPoles2.SetValue(4, aPole7); + // Make a BSpline curves from the point arrays + Handle(Geom_BSplineCurve) aBSplineCurve1 = GeomAPI_PointsToBSpline(aPoles1).Curve(); + Handle(Geom_BSplineCurve) aBSplineCurve2 = GeomAPI_PointsToBSpline(aPoles2).Curve(); + // Make edges + TopoDS_Edge anEdge1 = BRepBuilderAPI_MakeEdge(aBSplineCurve1); + TopoDS_Edge anEdge2 = BRepBuilderAPI_MakeEdge(aBSplineCurve2); + // Make a wire + BRepBuilderAPI_MakeWire aMakeWire; + aMakeWire.Add(anEdge1); + aMakeWire.Add(anEdge2); + Standard_ASSERT_VOID(aMakeWire.IsDone(), "Added edge isn't connectible!"); + TopoDS_Wire aWire = aMakeWire.Wire(); + myResult << "Wire of two BSpline curves was created" << std::endl; + + Handle(AIS_ColoredShape) anAisWire = new AIS_ColoredShape(aWire); + myObject3d.Append(anAisWire); + + // Make an adaptor. + BRepAdaptor_CompCurve aCurveAdaptor(aWire); + + // Use the curve adaptor for some calculations, e.g. compute + // a set of points using GCPnts_QuasiUniformDeflection algo. + Standard_Real aDeflection = 0.5; + GCPnts_QuasiUniformDeflection anAlgo(aCurveAdaptor, aDeflection); + Standard_ASSERT_VOID(anAlgo.IsDone(), "Success is expected!"); + myResult << "Distribution of point on the curve with " << aDeflection + << " deflection was performed:" << std::endl; + for (Standard_Integer i = 1; i <= anAlgo.NbPoints(); ++i) + { + gp_Pnt aPnt = anAlgo.Value(i); + myResult << "Point #" << i << " : [ " + << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z() << " ]" << std::endl; + Handle(AIS_Point) anAisPnt = new AIS_Point(new Geom_CartesianPoint(aPnt)); + myObject3d.Append(anAisPnt); + } +} + +void TopologySamples::AssessToSurface3dSample() +{ + // Make a face from a sphere. + gp_Sphere aSphere(gp::XOY(), 4.0); + TopoDS_Face aFace = BRepBuilderAPI_MakeFace(aSphere); + myResult << "TopoDS_Face on the sphere with" << std::endl + << "the center at [ " + << aSphere.Location().X() << ", " << aSphere.Location().Y() << ", " << aSphere.Location().Z() + << " ] and R = " << aSphere.Radius() << " was created in yellow" << std::endl + << std::endl; + + // Make a surface adaptor. + BRepAdaptor_Surface aSurfAdaptor(aFace); + + // Use the surface adaptor for some calculations, e.g. compute + // a normal vector at a surface point. + Standard_Real anU = 0.0, aV = 0.0; + gp_Pnt aPnt; + gp_Vec aDU, aDV; + aSurfAdaptor.D1(anU, aV, aPnt, aDU, aDV); + gp_Vec aNorm = aDU.Crossed(aDV); + Standard_ASSERT_VOID(aNorm.Magnitude() > Precision::Confusion(), "Non zero vector is expected!"); + aNorm.Normalize(); + myResult << "Normal vector at ( " << anU << ", " << aV << " )" << std::endl + << " = " << aNorm.X() << ", " << aNorm.Y() << ", " << aNorm.Z() << " ] is in red" << std::endl; + + Handle(AIS_ColoredShape) anAisFace = new AIS_ColoredShape(aFace); + anAisFace->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + Handle(AIS_Point) anAisPnt = new AIS_Point(new Geom_CartesianPoint(aPnt)); + Handle(AIS_ColoredShape) anAisNorm = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aPnt, aPnt.XYZ() + aNorm.XYZ())); + myObject3d.Append(anAisFace); + myObject3d.Append(anAisNorm); + myObject3d.Append(anAisPnt); +} + +void TopologySamples::Common3dSample() +{ + // Make a box #1 with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + TopoDS_Shape aShape1 = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wireframe" << std::endl; + + // Make a box #2 by two points. + gp_Pnt aPnt1(5.0, 7.5, 10.0); + gp_Pnt aPnt2(20.0, 25.0, 30.0); + TopoDS_Shape aShape2 = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in green wirefreme" << std::endl; + + // Create a boolean algo. + BRepAlgoAPI_Common anAlgo(aShape1, aShape2); + + // Make operation. + anAlgo.Build(); + + if (!anAlgo.IsDone()) // Process errors + { + myResult << "Errors : " << std::endl; + anAlgo.DumpErrors(myResult); + } + if (anAlgo.HasWarnings()) // Process warnings + { + myResult << "Warnings : " << std::endl; + anAlgo.DumpErrors(myResult); + } + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResultShape = anAlgo.Shape(); + myResult << "Result shape was created in red shading" << std::endl; + + Handle(AIS_ColoredShape) anAisShape1 = new AIS_ColoredShape(aShape1); + Handle(AIS_ColoredShape) anAisShape2 = new AIS_ColoredShape(aShape2); + anAisShape1->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisShape2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResultShape); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisShape1); + myObject3d.Append(anAisShape2); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisShape1, 0, Standard_True); + myContext->SetDisplayMode(anAisShape2, 0, Standard_True); + myContext->SetDisplayMode(anAisResult, 1, Standard_True); + } +} + +void TopologySamples::Cut3dSample() +{ + // Make a box #1 with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + TopoDS_Shape aShape1 = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wireframe" << std::endl; + + // Make a box #2 by two points as a cutting tool. + gp_Pnt aPnt1(5.0, 7.5, 10.0); + gp_Pnt aPnt2(20.0, 25.0, 30.0); + TopoDS_Shape aShape2 = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in green wireframe" << std::endl; + + // Create a boolean algo. + BRepAlgoAPI_Cut anAlgo(aShape1, aShape2); + + // Make operation. + anAlgo.Build(); + + if (!anAlgo.IsDone()) // Process errors + { + myResult << "Errors : " << std::endl; + anAlgo.DumpErrors(myResult); + } + if (anAlgo.HasWarnings()) // Process warnings + { + myResult << "Warnings : " << std::endl; + anAlgo.DumpErrors(myResult); + } + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResultShape = anAlgo.Shape(); + myResult << "Result shape was created in red shading" << std::endl; + Handle(AIS_ColoredShape) anAisShape1 = new AIS_ColoredShape(aShape1); + Handle(AIS_ColoredShape) anAisShape2 = new AIS_ColoredShape(aShape2); + anAisShape1->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisShape2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResultShape); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisShape1); + myObject3d.Append(anAisShape2); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisShape1, 0, Standard_True); + myContext->SetDisplayMode(anAisShape2, 0, Standard_True); + myContext->SetDisplayMode(anAisResult, 1, Standard_True); + } +} + +void TopologySamples::Fuse3dSample() +{ + // Make a box #1 with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + TopoDS_Shape aShape1 = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wireframe" << std::endl; + + // Make a box #2 by two points. + gp_Pnt aPnt1(5.0, 7.5, 10.0); + gp_Pnt aPnt2(20.0, 25.0, 30.0); + TopoDS_Shape aShape2 = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in green wireframe" << std::endl; + + // Create a boolean algo. + BRepAlgoAPI_Fuse anAlgo(aShape1, aShape2); + + // Make operation. + anAlgo.Build(); + + if (!anAlgo.IsDone()) // Process errors + { + myResult << "Errors : " << std::endl; + anAlgo.DumpErrors(myResult); + } + if (anAlgo.HasWarnings()) // Process warnings + { + myResult << "Warnings : " << std::endl; + anAlgo.DumpErrors(myResult); + } + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResultShape = anAlgo.Shape(); + myResult << "Result shape was created in red shading" << std::endl; + Handle(AIS_ColoredShape) anAisShape1 = new AIS_ColoredShape(aShape1); + Handle(AIS_ColoredShape) anAisShape2 = new AIS_ColoredShape(aShape2); + anAisShape1->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisShape2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResultShape); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisShape1); + myObject3d.Append(anAisShape2); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisShape1, 0, Standard_True); + myContext->SetDisplayMode(anAisShape2, 0, Standard_True); + myContext->SetDisplayMode(anAisResult, 1, Standard_True); + } +} + +void TopologySamples::Section3dSample() +{ + // Make a box #1 with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + TopoDS_Shape aShape = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wireframe" << std::endl; + + // Create a boolean algo. + // Make a section by a plane. + gp_Pln aPln(gp_Pnt(aSizeX / 2.0, aSizeY / 2.0, aSizeZ / 2.0), gp::DZ()); + BRepAlgoAPI_Section anAlgo(aShape, aPln, Standard_False); + + // Make operation. + anAlgo.Build(); + + if (!anAlgo.IsDone()) // Process errors + { + myResult << "Errors : " << std::endl; + anAlgo.DumpErrors(myResult); + } + if (anAlgo.HasWarnings()) // Process warnings + { + myResult << "Warnings : " << std::endl; + anAlgo.DumpErrors(myResult); + } + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResultShape = anAlgo.Shape(); + myResult << "Result shape was created in red" << std::endl; + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + Handle(AIS_Plane) anAisPlane = new AIS_Plane(new Geom_Plane(aPln)); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResultShape); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisShape); + myObject3d.Append(anAisPlane); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisShape, 0, Standard_True); + } +} + +void TopologySamples::Splitter3dSample() +{ + // Make a box by two points. + gp_Pnt aPnt1(-5.0, -7.5, -10.0); + gp_Pnt aPnt2(10.0, 15.0, 10.0); + TopoDS_Shape aBox = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" + << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" + << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in yellow" << std::endl; + + // Make a splitting tool as XY plane. + TopoDS_Shape aTool = BRepBuilderAPI_MakeFace(gp_Pln(gp::XOY())); + + // Create a splitter algo. + BRepAlgoAPI_Splitter aSplitter; + + // Add shapes to be split. + TopTools_ListOfShape anArguments; + anArguments.Append(aBox); + aSplitter.SetArguments(anArguments); + + // Add tool shapes. + TopTools_ListOfShape aTools; + aTools.Append(aTool); + aSplitter.SetTools(aTools); + + // Perform splitting. + aSplitter.Build(); + + if (!aSplitter.IsDone()) // Process errors + { + myResult << "Errors : " << std::endl; + aSplitter.DumpErrors(myResult); + } + if (aSplitter.HasWarnings()) // Process warnings + { + myResult << "Warnings : " << std::endl; + aSplitter.DumpErrors(myResult); + } + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisBox); + + if (aSplitter.IsDone()) // Process results + { + // Simplification of the result shape is performed by the means of + // ShapeUpgrade_UnifySameDomain algorithm. The result of the operation will + // be overwritten with the simplified result. + // The simplification is performed without creation of the Internal shapes, + // i.e. shapes connections will never be broken. + // Simplification is performed on the whole result shape. Thus, if the input + // shapes contained connected tangent edges or faces unmodified during the operation + // they will also be unified. + aSplitter.SimplifyResult(); + + // Get result of splitting. + TopoDS_Shape aResult = aSplitter.Shape(); + myResult << "Splitting result (shapes are moved apart for illustativeness) is in red" << std::endl; + + // In this particular sample two shapes in the result are expected. + // Lets move apart them for illustrative purposes. + TopoDS_Iterator anIt(aResult); + Standard_ASSERT_VOID(anIt.More(), "Not empty result is expected!"); + TopoDS_Shape aBox1 = anIt.Value(); anIt.Next(); + Standard_ASSERT_VOID(anIt.More(), "Two shapes in the result are expected!"); + TopoDS_Shape aBox2 = anIt.Value(); + gp_Trsf aTrsf1; aTrsf1.SetTranslation(gp_Vec(0.0, 0.0, -15.0)); + aBox1.Move(aTrsf1); + gp_Trsf aTrsf2; aTrsf2.SetTranslation(gp_Vec(0.0, 0.0, +15.0)); + aBox2.Move(aTrsf2); + + Handle(AIS_ColoredShape) anAisBox1 = new AIS_ColoredShape(aBox1); + Handle(AIS_ColoredShape) anAisBox2 = new AIS_ColoredShape(aBox2); + anAisBox1->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisBox2->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBox1); + myObject3d.Append(anAisBox2); + } +} + +void TopologySamples::Defeaturing3dSample() +{ + // Prepare a box with a chamfer. + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 8.0; + Standard_Real aSizeY = 10.0; + Standard_Real aSizeZ = 15.0; + TopoDS_Shape aBox = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + // Initialize chamfer algo. + BRepFilletAPI_MakeChamfer anAlgo(aBox); + // Set edge to apply a chamfer with specified distance from it. + // Select the 5th edge in the map returned by TopExp::MapShapes method. + TopTools_IndexedMapOfShape anEdges; + TopExp::MapShapes(aBox, TopAbs_EDGE, anEdges); + TopoDS_Edge anEdge = TopoDS::Edge(anEdges.FindKey(5)); + Standard_Real aDist = 4.0; + anAlgo.Add(aDist, anEdge); + // Make a chamfer. + anAlgo.Build(); + Standard_ASSERT_VOID(anAlgo.IsDone(), "Couldn't prepare a box with a chamfer!"); + // Get a box with a chamfer. + TopoDS_Shape aBoxWithChamfer = anAlgo.Shape(); + myResult << "Box with a chamfer is in yellow shading" << std::endl; + + Handle(AIS_ColoredShape) anAisBoxWithChamfer = new AIS_ColoredShape(aBoxWithChamfer); + anAisBoxWithChamfer->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisBoxWithChamfer); + myContext->SetDisplayMode(anAisBoxWithChamfer, 1, Standard_True); + + // Retrieve chamfer faces generated from the edge + const TopTools_ListOfShape& aGenShapes = anAlgo.Generated(anEdge); + Standard_ASSERT_VOID(!aGenShapes.IsEmpty(), "Chamfer face is expected!"); + for (TopTools_ListOfShape::Iterator anIt(aGenShapes); anIt.More(); anIt.Next()) + { + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(anIt.Value()); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisShape->SetWidth(2.5); + myObject3d.Append(anAisShape); + myContext->SetDisplayMode(anAisBoxWithChamfer, 1, Standard_True); + } + myResult << "Chamfer faces : " << aGenShapes.Size() << std::endl; + myResult << "The first one is using to remove" << std::endl; + myResult << "The removed face is in green" << std::endl; + + // Initialize defeaturing algo. + BRepAlgoAPI_Defeaturing aDefeatAlgo; + aDefeatAlgo.SetShape(aBoxWithChamfer); + aDefeatAlgo.AddFaceToRemove(aGenShapes.First()); + + // Remove the chamfer. + aDefeatAlgo.Build(); + + if (aDefeatAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResult = aDefeatAlgo.Shape(); + myResult << "Defeatured box is in red wireframe" << std::endl; + + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResult); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisResult, 0, Standard_True); + } +} + +void TopologySamples::Fillet3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 8.0; + Standard_Real aSizeY = 10.0; + Standard_Real aSizeZ = 15.0; + TopoDS_Shape aBox = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wireframe" << std::endl; + + // Initialize fillet algo. + BRepFilletAPI_MakeFillet anAlgo(aBox); + + // Set edge to apply a fillet with specified radius. + // Select the first edge in the map returned by TopExp::MapShapes method. + TopTools_IndexedMapOfShape anEdges; + TopExp::MapShapes(aBox, TopAbs_EDGE, anEdges); + TopoDS_Edge anEdge = TopoDS::Edge(anEdges.FindKey(1)); + Standard_Real aRadius = 3.0; + anAlgo.Add(aRadius, anEdge); + myResult << "Make a fillet of " << aRadius << " radius on an edge in green" << std::endl; + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + Handle(AIS_ColoredShape) anAisEdge = new AIS_ColoredShape(anEdge); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEdge->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisEdge->SetWidth(2.5); + myObject3d.Append(anAisBox); + myObject3d.Append(anAisEdge); + myContext->SetDisplayMode(anAisBox, 0, Standard_True); + + // Make a fillet. + anAlgo.Build(); + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResult = anAlgo.Shape(); + myResult << "Fillet was built. Result shape is in red shading" << std::endl; + + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResult); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisResult, 1, Standard_True); + } +} + +void TopologySamples::Chamfer3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 8.0; + Standard_Real aSizeY = 10.0; + Standard_Real aSizeZ = 15.0; + TopoDS_Shape aBox = BRepPrimAPI_MakeBox(aSizeX, aSizeY, aSizeZ); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow wirewrame" << std::endl; + + // Initialize chamfer algo. + BRepFilletAPI_MakeChamfer anAlgo(aBox); + + // Set edge to apply a chamfer with specified distance from it. + // Select the 5th edge in the map returned by TopExp::MapShapes method. + TopTools_IndexedMapOfShape anEdges; + TopExp::MapShapes(aBox, TopAbs_EDGE, anEdges); + TopoDS_Edge anEdge = TopoDS::Edge(anEdges.FindKey(5)); + Standard_Real aDist = 4.0; + anAlgo.Add(aDist, anEdge); + myResult << "Make a chamfer of " << aDist << " size on an edge in green" << std::endl; + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + Handle(AIS_ColoredShape) anAisEdge = new AIS_ColoredShape(anEdge); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisEdge->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisEdge->SetWidth(2.5); + myObject3d.Append(anAisBox); + myObject3d.Append(anAisEdge); + myContext->SetDisplayMode(anAisBox, 0, Standard_True); + + // Make a chamfer. + anAlgo.Build(); + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResult = anAlgo.Shape(); + myResult << "Fillet was built. Result shape is in red shading" << std::endl; + + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResult); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisResult); + myContext->SetDisplayMode(anAisResult, 1, Standard_True); + + const TopTools_ListOfShape& aGenShapes = anAlgo.Generated(anEdge); + for (TopTools_ListOfShape::Iterator anIt(aGenShapes); anIt.More(); anIt.Next()) + { + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(anIt.Value()); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_RED)); + anAisShape->SetWidth(2.5); + myObject3d.Append(anAisShape); + } + } +} + +void TopologySamples::Offset3dSample() +{ + // Make a triangle wire. + BRepBuilderAPI_MakePolygon aTria; + TopoDS_Vertex aVertA = BRepBuilderAPI_MakeVertex(gp_Pnt(-0.5, 0.0, 0.0)); + TopoDS_Vertex aVertB = BRepBuilderAPI_MakeVertex(gp_Pnt(0.0, 0.0, +1.0)); + TopoDS_Vertex aVertC = BRepBuilderAPI_MakeVertex(gp_Pnt(+0.5, 0.0, 0.0)); + aTria.Add(aVertA); + aTria.Add(aVertB); + aTria.Add(aVertC); + aTria.Close(); + TopoDS_Wire aWire = aTria.Wire(); + myResult << "Trianglular wire was created in yellow" << std::endl; + + Handle(AIS_ColoredShape) anAisWire = new AIS_ColoredShape(aWire); + anAisWire->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + myObject3d.Append(anAisWire); + + // Initialize offset algo. + BRepOffsetAPI_MakeOffset anAlgo(aWire); + + // Perform a series of offsets with linearly increasing value and altitude. + Standard_Real anOffsetStep = 0.2; + Standard_Real anAltitudeStep = 0.1; + for (Standard_Integer i = 1; i <= 4; ++i) + { + Standard_Real anOffset = anOffsetStep * i; + Standard_Real anAltitude = anAltitudeStep * i; + anAlgo.Perform(anOffset, anAltitude); + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResult = anAlgo.Shape(); + myResult << "#" << i << " : Offest = " << anOffset << " Altitude = " << anAltitude + << ". Result is in red." << std::endl; + + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResult); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisResult); + } + } +} + +void TopologySamples::Evolved3dSample() +{ + // Make a triangle wire as a spine. + BRepBuilderAPI_MakePolygon aTria; + TopoDS_Vertex aVertA = BRepBuilderAPI_MakeVertex(gp_Pnt(-0.5, 0.0, 0.0)); + TopoDS_Vertex aVertB = BRepBuilderAPI_MakeVertex(gp_Pnt(0.0, +1.0, 0.0)); + TopoDS_Vertex aVertC = BRepBuilderAPI_MakeVertex(gp_Pnt(+0.5, 0.0, 0.0)); + aTria.Add(aVertA); + aTria.Add(aVertB); + aTria.Add(aVertC); + aTria.Close(); + TopoDS_Wire aSpine = aTria.Wire(); + myResult << "Profile wire was created in yellow" << std::endl; + + // Make a wire as a profile. + BRepBuilderAPI_MakePolygon aPoly; + TopoDS_Vertex aVert1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-0.5, 0.0, 0.0)); + TopoDS_Vertex aVert2 = BRepBuilderAPI_MakeVertex(gp_Pnt(-0.5, -0.1, 0.5)); + TopoDS_Vertex aVert3 = BRepBuilderAPI_MakeVertex(gp_Pnt(-0.5, -0.2, 1.0)); + aPoly.Add(aVert1); + aPoly.Add(aVert2); + aPoly.Add(aVert3); + TopoDS_Wire aProfile = aPoly.Wire(); + myResult << "Spine wire was created in greed" << std::endl; + + Handle(AIS_ColoredShape) anAisSpine = new AIS_ColoredShape(aSpine); + Handle(AIS_ColoredShape) anAisProfile = new AIS_ColoredShape(aProfile); + anAisSpine->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisSpine->SetWidth(2.5); + anAisProfile->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisProfile->SetWidth(2.5); + myObject3d.Append(anAisSpine); + myObject3d.Append(anAisProfile); + + // Initialize evolving algo. + GeomAbs_JoinType aJoinType = GeomAbs_Arc; + Standard_Boolean aIsGlobalCS = Standard_False; + Standard_Boolean aIsSolid = Standard_True; + BRepOffsetAPI_MakeEvolved anAlgo(aSpine, aProfile, aJoinType, aIsGlobalCS, aIsSolid); + + // Perform evolving. + anAlgo.Build(); + + if (anAlgo.IsDone()) + { + // Get result. + TopoDS_Shape aResult = anAlgo.Shape(); + myResult << "Evolving result is in red" << std::endl; + + Handle(AIS_ColoredShape) anAisResult = new AIS_ColoredShape(aResult); + anAisResult->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisResult); + } +} + +void TopologySamples::Copy3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + BRepPrimAPI_MakeBox aBoxMake(aSizeX, aSizeY, aSizeZ); + TopoDS_Shape aBox = aBoxMake.Shape(); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow" << std::endl; + + // Make a box copy. + TopoDS_Shape aBoxCopy = BRepBuilderAPI_Copy(aBox); + myResult << "Box copy was created in red" << std::endl; + + gp_Trsf aTrsf1; aTrsf1.SetTranslation(gp_Vec(15.0, 0.0, 0.0)); + aBoxCopy.Move(aTrsf1); + myResult << "Box copy shape is moved apart for illustativeness" << std::endl; + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisBox->SetWidth(2.5); + Handle(AIS_ColoredShape) anAisBoxCopy = new AIS_ColoredShape(aBoxCopy); + anAisBoxCopy->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBox); + myObject3d.Append(anAisBoxCopy); +} + +void TopologySamples::Transform3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + BRepPrimAPI_MakeBox aBoxMake(aSizeX, aSizeY, aSizeZ); + TopoDS_Shape aBox = aBoxMake.Shape(); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow" << std::endl; + + // Move the box. + gp_Trsf aTrMove; aTrMove.SetTranslation(gp_Vec(15.0, 20.0, 25.0)); + TopoDS_Shape aMovedBox = BRepBuilderAPI_Transform(aBox, aTrMove, Standard_True); + myResult << "Moved box in green" << std::endl; + + // Rotate the moved box + gp_Trsf aTrRot; aTrRot.SetRotation(gp_Ax1(gp_Pnt(15.0, 20.0, 25.0), gp::DZ()), 3.0*M_PI_4); + TopoDS_Shape aRotatedBox = BRepBuilderAPI_Transform(aBox, aTrRot, Standard_True); + myResult << "Rotated box in red" << std::endl; + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + Handle(AIS_ColoredShape) anAisMovedBox = new AIS_ColoredShape(aMovedBox); + Handle(AIS_ColoredShape) anAisRotatedBox = new AIS_ColoredShape(aRotatedBox); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisMovedBox->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + anAisRotatedBox->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBox); + myObject3d.Append(anAisMovedBox); + myObject3d.Append(anAisRotatedBox); +} + +void TopologySamples::ConvertToNurbs3dSample() +{ + // Make a torus face. + gp_Torus aTorus(gp::XOY(), 20.0, 7.5); + TopoDS_Shape aTorusFace = BRepBuilderAPI_MakeFace(aTorus); + myResult << "TopoDS_Solid on the torus with" << std::endl + << "R major = " << aTorus.MajorRadius() << std::endl + << "R minor = " << aTorus.MinorRadius() << std::endl + << "was created in yellow" << std::endl; + + // Convert faces/edges from analytic to NURBS geometry. + TopoDS_Shape aNurbsFace = BRepBuilderAPI_NurbsConvert(aTorusFace); + myResult << "Converted torus in red" << std::endl; + gp_Trsf aTrsf1; aTrsf1.SetTranslation(gp_Vec(60.0, 0.0, 0.0)); + aNurbsFace.Move(aTrsf1); + myResult << "Converted torus is moved apart for illustativeness" << std::endl; + + Handle(AIS_ColoredShape) anAisTorus = new AIS_ColoredShape(aTorusFace); + Handle(AIS_ColoredShape) anAisNurbs = new AIS_ColoredShape(aNurbsFace); + anAisTorus->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisTorus->SetWidth(2.5); + anAisNurbs->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisTorus); + myObject3d.Append(anAisNurbs); +} + +void TopologySamples::SewContiguousFaces3dSample() +{ + // Make a sphere. + gp_Sphere aSphere(gp::XOY(), 1.0); + // South hemisphere. + TopoDS_Face aFace1 = BRepBuilderAPI_MakeFace(aSphere, 0.0, 2.0 * M_PI, -M_PI_2, 0.0); + // North hemisphere. + TopoDS_Face aFace2 = BRepBuilderAPI_MakeFace(aSphere, 0.0, 2.0 * M_PI, 0.0, +M_PI_2); + + // Make a default tailor. + BRepBuilderAPI_Sewing aTailor; + + // Add hemisphere faces. + aTailor.Add(aFace1); + aTailor.Add(aFace2); + + // Perform sewing. + aTailor.Perform(); + + // Get result. + const TopoDS_Shape& aSewedSphere = aTailor.SewedShape(); + myResult << "Two hemispheres were sewed : " << aTailor.NbFreeEdges() << " free edges" << std::endl; + + Handle(AIS_ColoredShape) anAisSewedSphere = new AIS_ColoredShape(aSewedSphere); + anAisSewedSphere->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisSewedSphere); +} + +void TopologySamples::CheckValidity3dSample() +{ + // Make a box with a corner at [0, 0, 0] and the specified sizes. + Standard_Real aSizeX = 10.0; + Standard_Real aSizeY = 15.0; + Standard_Real aSizeZ = 20.0; + BRepPrimAPI_MakeBox aBoxMake(aSizeX, aSizeY, aSizeZ); + TopoDS_Shape aBox = aBoxMake.Shape(); + myResult << "Box at corner [0, 0, 0] and sizes [" + << aSizeX << ", " << aSizeY << ", " << aSizeZ + << "] was created in yellow" << std::endl; + + // Analyze the box. + BRepCheck_Analyzer anAnalyzer(aBox); + myResult << "Box is " << (anAnalyzer.IsValid() ? "valid" : "invalid") << std::endl; + + // Make the box invalid manually. + Handle(BRepTools_ReShape) aReShape = new BRepTools_ReShape(); + myResult << "Remove the top face from the box (red)" << std::endl; + aReShape->Remove(aBoxMake.TopFace()); + TopoDS_Shape aBox1 = aReShape->Apply(aBox); + myResult << "The top face was removed" << std::endl; + + // Analyze the modified box. + BRepCheck_Analyzer anAnalyzer1(aBox1); + myResult << "Modified box is " << (anAnalyzer1.IsValid() ? "valid" : "invalid") << std::endl; + + Handle(AIS_ColoredShape) anAisBox = new AIS_ColoredShape(aBox); + Handle(AIS_ColoredShape) anAisTopFace = new AIS_ColoredShape(aBoxMake.TopFace()); + anAisBox->SetColor(Quantity_Color(Quantity_NOC_YELLOW)); + anAisTopFace->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject3d.Append(anAisBox); + myObject3d.Append(anAisTopFace); +} + +void TopologySamples::ComputeLinearProperties3dSample() +{ + // Make an edge from a circular segment. + // Create a circle in XY plane of the radius 1.0. + gp_Circ aCirc(gp::XOY(), 1.0); + // Make a circular edge from the 1st quoter in the parametric space. + TopoDS_Edge aShape = BRepBuilderAPI_MakeEdge(aCirc, 0.0, M_PI); + myResult << "TopoDS_Edge on the circle's 1st quoter" << std::endl + << "with the center at [ " + << aCirc.Location().X() << ", " << aCirc.Location().Y() << ", " << aCirc.Location().Z() + << " ] and R = " << aCirc.Radius() << " was created in red" << std::endl + << std::endl; + + // Retrieve linear properties from the edge. + GProp_GProps aGProps; + BRepGProp::LinearProperties(aShape, aGProps); + Standard_Real aLength = aGProps.Mass(); + gp_Pnt aCOM = aGProps.CentreOfMass(); + Standard_Real anIx, anIy, anIz; + aGProps.StaticMoments(anIx, anIy, anIz); + gp_Mat aMOI = aGProps.MatrixOfInertia(); + myResult << "Linear properties:" << std::endl + << " Length = " << aLength << std::endl + << " Center of mass = [ " << aCOM.X() << ", " << aCOM.Y() << ", " << aCOM.Z() << " ]" << std::endl + << " Static moments = [ " << anIx << ", " << anIy << ", " << anIz << " ]" << std::endl + << " Matrix of inertia = [ " + << aMOI(1, 1) << ", " << aMOI(1, 2) << ", " << aMOI(1, 3) << std::endl + << std::setw(33) << aMOI(2, 1) << ", " << aMOI(2, 2) << ", " << aMOI(2, 3) << std::endl + << std::setw(33) << aMOI(3, 1) << ", " << aMOI(3, 2) << ", " << aMOI(3, 3) << " ]" << std::endl; + GProp_PrincipalProps aPProps = aGProps.PrincipalProperties(); + Standard_Real anIxx, anIyy, anIzz; + aPProps.Moments(anIxx, anIyy, anIzz); + Standard_Real aRxx, aRyy, aRzz; + aPProps.RadiusOfGyration(aRxx, aRyy, aRzz); + myResult << "Principal properties:" << std::endl + << " Has symmetric axis : " << (aPProps.HasSymmetryAxis() ? "YES" : "NO") << std::endl + << " Has symmetric point : " << (aPProps.HasSymmetryPoint() ? "YES" : "NO") << std::endl + << " Moments of inertia = [ " << anIxx << ", " << anIyy << ", " << anIzz << " ]" << std::endl + << " Radius of gyration = [ " << aRxx << ", " << aRyy << ", " << aRzz << " ]" << std::endl; + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis1 = aPProps.FirstAxisOfInertia(); + myResult << " 1st axis of inertia = [ " << anAxis1.X() << ", " << anAxis1.Y() << ", " << anAxis1.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis1 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis1.XYZ())); + anAisAxis1->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis1); + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis2 = aPProps.SecondAxisOfInertia(); + myResult << " 2nd axis of inertia = [ " << anAxis2.X() << ", " << anAxis2.Y() << ", " << anAxis2.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis2 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis2.XYZ())); + anAisAxis2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis2); + const gp_Vec& anAxis3 = aPProps.ThirdAxisOfInertia(); + myResult << " 3rd axis of inertia = [ " << anAxis3.X() << ", " << anAxis3.Y() << ", " << anAxis3.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis3 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis3.XYZ())); + anAisAxis3->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis3); + } + } + + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + Handle(AIS_Point) anAisCOM = new AIS_Point(new Geom_CartesianPoint(aCOM)); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_RED)); + Handle(AIS_TextLabel) aCOMLabel = new AIS_TextLabel(); + aCOMLabel->SetText("Center of mass"); + aCOMLabel->SetPosition(aCOM); + Handle(AIS_Axis) anAisAxisX = new AIS_Axis(new Geom_Axis2Placement(gp::YOZ()), AIS_TOAX_XAxis); + Handle(AIS_Axis) anAisAxisY = new AIS_Axis(new Geom_Axis2Placement(gp::ZOX()), AIS_TOAX_YAxis); + Handle(AIS_Axis) anAisAxisZ = new AIS_Axis(new Geom_Axis2Placement(gp::XOY()), AIS_TOAX_ZAxis); + myObject3d.Append(anAisAxisX); + myObject3d.Append(anAisAxisY); + myObject3d.Append(anAisAxisZ); + myObject3d.Append(anAisShape); + myObject3d.Append(anAisCOM); + myObject3d.Append(aCOMLabel); +} + +void TopologySamples::ComputeSurfaceProperties3dSample() +{ + // Make a face from a cylinder with R = 1 + // and directed along Z axis + gp_Cylinder aCyl(gp::XOY(), 1.0); + TopoDS_Face aShape = BRepBuilderAPI_MakeFace(aCyl, 0.0, M_PI, -1.0, +1.0).Face(); + myResult << "TopoDS_Face on the cylinder R = " << aCyl.Radius() << std::endl + << "with axis [ " << aCyl.Position().Direction().X() << ", " << aCyl.Position().Direction().Y() << ", " << aCyl.Position().Direction().Z() << " ]" << std::endl + << "limited in length [-1 ... +1] was created in red" << std::endl; + + // Retrieve surface properties from the face. + GProp_GProps aGProps; + BRepGProp::SurfaceProperties(aShape, aGProps); + Standard_Real aArea = aGProps.Mass(); + gp_Pnt aCOM = aGProps.CentreOfMass(); + Standard_Real anIx, anIy, anIz; + aGProps.StaticMoments(anIx, anIy, anIz); + gp_Mat aMOI = aGProps.MatrixOfInertia(); + myResult << "Linear properties:" << std::endl + << " Area = " << aArea << std::endl + << " Center of mass = [ " << aCOM.X() << ", " << aCOM.Y() << ", " << aCOM.Z() << " ]" << std::endl + << " Static moments = [ " << anIx << ", " << anIy << ", " << anIz << " ]" << std::endl + << " Matrix of inertia = [ " + << aMOI(1, 1) << ", " << aMOI(1, 2) << ", " << aMOI(1, 3) << std::endl + << std::setw(33) << aMOI(2, 1) << ", " << aMOI(2, 2) << ", " << aMOI(2, 3) << std::endl + << std::setw(33) << aMOI(3, 1) << ", " << aMOI(3, 2) << ", " << aMOI(3, 3) << " ]" << std::endl; + GProp_PrincipalProps aPProps = aGProps.PrincipalProperties(); + Standard_Real anIxx, anIyy, anIzz; + aPProps.Moments(anIxx, anIyy, anIzz); + Standard_Real aRxx, aRyy, aRzz; + aPProps.RadiusOfGyration(aRxx, aRyy, aRzz); + myResult << "Principal properties:" << std::endl + << " Has symmetric axis : " << (aPProps.HasSymmetryAxis() ? "YES" : "NO") << std::endl + << " Has symmetric point : " << (aPProps.HasSymmetryPoint() ? "YES" : "NO") << std::endl + << " Moments of inertia = [ " << anIxx << ", " << anIyy << ", " << anIzz << " ]" << std::endl + << " Radius of gyration = [ " << aRxx << ", " << aRyy << ", " << aRzz << " ]" << std::endl; + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis1 = aPProps.FirstAxisOfInertia(); + myResult << " 1st axis of inertia = [ " << anAxis1.X() << ", " << anAxis1.Y() << ", " << anAxis1.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis1 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis1.XYZ())); + anAisAxis1->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis1); + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis2 = aPProps.SecondAxisOfInertia(); + myResult << " 2nd axis of inertia = [ " << anAxis2.X() << ", " << anAxis2.Y() << ", " << anAxis2.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis2 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis2.XYZ())); + anAisAxis2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis2); + const gp_Vec& anAxis3 = aPProps.ThirdAxisOfInertia(); + myResult << " 3rd axis of inertia = [ " << anAxis3.X() << ", " << anAxis3.Y() << ", " << anAxis3.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis3 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis3.XYZ())); + anAisAxis3->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis3); + } + } + + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + Handle(AIS_Point) anAisCOM = new AIS_Point(new Geom_CartesianPoint(aCOM)); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_RED)); + Handle(AIS_TextLabel) aCOMLabel = new AIS_TextLabel(); + aCOMLabel->SetText("Center of mass"); + aCOMLabel->SetPosition(aCOM); + Handle(AIS_Axis) anAisAxisX = new AIS_Axis(new Geom_Axis2Placement(gp::YOZ()), AIS_TOAX_XAxis); + Handle(AIS_Axis) anAisAxisY = new AIS_Axis(new Geom_Axis2Placement(gp::ZOX()), AIS_TOAX_YAxis); + Handle(AIS_Axis) anAisAxisZ = new AIS_Axis(new Geom_Axis2Placement(gp::XOY()), AIS_TOAX_ZAxis); + myObject3d.Append(anAisAxisX); + myObject3d.Append(anAisAxisY); + myObject3d.Append(anAisAxisZ); + myObject3d.Append(anAisShape); + myObject3d.Append(anAisCOM); + myObject3d.Append(aCOMLabel); +} + +void TopologySamples::ComputeVolumeProperties3dSample() +{ + // Make a box by two points. + gp_Pnt aPnt1(-0.5, -0.6, -0.7); + gp_Pnt aPnt2(+0.8, +0.9, +1.0); + TopoDS_Shape aShape = BRepPrimAPI_MakeBox(aPnt1, aPnt2); + myResult << "Box with corners [" << aPnt1.X() << ", " << aPnt1.Y() << ", " << aPnt1.Z() + << "] and [" << aPnt2.X() << ", " << aPnt2.Y() << ", " << aPnt2.Z() + << "] was created in red" << std::endl; + + // Retrieve volume properties from the face. + GProp_GProps aGProps; + BRepGProp::VolumeProperties(aShape, aGProps); + Standard_Real aVolume = aGProps.Mass(); + gp_Pnt aCOM = aGProps.CentreOfMass(); + Standard_Real anIx, anIy, anIz; + aGProps.StaticMoments(anIx, anIy, anIz); + gp_Mat aMOI = aGProps.MatrixOfInertia(); + myResult << "Linear properties:" << std::endl + << " Volume = " << aVolume << std::endl + << " Center of mass = [ " << aCOM.X() << ", " << aCOM.Y() << ", " << aCOM.Z() << " ]" << std::endl + << " Static moments = [ " << anIx << ", " << anIy << ", " << anIz << " ]" << std::endl + << " Matrix of inertia = [ " + << aMOI(1, 1) << ", " << aMOI(1, 2) << ", " << aMOI(1, 3) << std::endl + << std::setw(33) << aMOI(2, 1) << ", " << aMOI(2, 2) << ", " << aMOI(2, 3) << std::endl + << std::setw(33) << aMOI(3, 1) << ", " << aMOI(3, 2) << ", " << aMOI(3, 3) << " ]" << std::endl; + GProp_PrincipalProps aPProps = aGProps.PrincipalProperties(); + Standard_Real anIxx, anIyy, anIzz; + aPProps.Moments(anIxx, anIyy, anIzz); + Standard_Real aRxx, aRyy, aRzz; + aPProps.RadiusOfGyration(aRxx, aRyy, aRzz); + myResult << "Principal properties:" << std::endl + << " Has symmetric axis : " << (aPProps.HasSymmetryAxis() ? "YES" : "NO") << std::endl + << " Has symmetric point : " << (aPProps.HasSymmetryPoint() ? "YES" : "NO") << std::endl + << " Moments of inertia = [ " << anIxx << ", " << anIyy << ", " << anIzz << " ]" << std::endl + << " Radius of gyration = [ " << aRxx << ", " << aRyy << ", " << aRzz << " ]" << std::endl; + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis1 = aPProps.FirstAxisOfInertia(); + myResult << " 1st axis of inertia = [ " << anAxis1.X() << ", " << anAxis1.Y() << ", " << anAxis1.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis1 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis1.XYZ())); + anAisAxis1->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis1); + if (!aPProps.HasSymmetryPoint()) + { + const gp_Vec& anAxis2 = aPProps.SecondAxisOfInertia(); + myResult << " 2nd axis of inertia = [ " << anAxis2.X() << ", " << anAxis2.Y() << ", " << anAxis2.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis2 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis2.XYZ())); + anAisAxis2->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis2); + const gp_Vec& anAxis3 = aPProps.ThirdAxisOfInertia(); + myResult << " 3rd axis of inertia = [ " << anAxis3.X() << ", " << anAxis3.Y() << ", " << anAxis3.Z() << " ]" << std::endl; + Handle(AIS_ColoredShape) anAisAxis3 = new AIS_ColoredShape( + BRepBuilderAPI_MakeEdge(aCOM, aCOM.XYZ() + anAxis3.XYZ())); + anAisAxis3->SetColor(Quantity_Color(Quantity_NOC_GREEN)); + myObject3d.Append(anAisAxis3); + } + } + + Handle(AIS_ColoredShape) anAisShape = new AIS_ColoredShape(aShape); + Handle(AIS_Point) anAisCOM = new AIS_Point(new Geom_CartesianPoint(aCOM)); + anAisShape->SetColor(Quantity_Color(Quantity_NOC_RED)); + Handle(AIS_TextLabel) aCOMLabel = new AIS_TextLabel(); + aCOMLabel->SetText("Center of mass"); + aCOMLabel->SetPosition(aCOM); + Handle(AIS_Axis) anAisAxisX = new AIS_Axis(new Geom_Axis2Placement(gp::YOZ()), AIS_TOAX_XAxis); + Handle(AIS_Axis) anAisAxisY = new AIS_Axis(new Geom_Axis2Placement(gp::ZOX()), AIS_TOAX_YAxis); + Handle(AIS_Axis) anAisAxisZ = new AIS_Axis(new Geom_Axis2Placement(gp::XOY()), AIS_TOAX_ZAxis); + myObject3d.Append(anAisAxisX); + myObject3d.Append(anAisAxisY); + myObject3d.Append(anAisAxisZ); + myObject3d.Append(anAisShape); + myObject3d.Append(anAisCOM); + myObject3d.Append(aCOMLabel); +} diff --git a/samples/OCCTOverview/code/TopologySamples.h b/samples/OCCTOverview/code/TopologySamples.h new file mode 100644 index 0000000000..ecb6ca51ac --- /dev/null +++ b/samples/OCCTOverview/code/TopologySamples.h @@ -0,0 +1,80 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef TOPOLOGYSAMPLES_H +#define TOPOLOGYSAMPLES_H + +#include "BaseSample.h" + +#include <AIS_InteractiveContext.hxx> + +//! Implements Topology samples +class TopologySamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(TopologySamples, BaseSample) +public: + + TopologySamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample(theSampleSourcePath, theContext) + {} + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + // One function for every sample + void Vertex3dSample(); + void Edge3dSample(); + void Face3dSample(); + void Wire3dSample(); + void Shell3dSample(); + void Solid3dSample(); + void Edge2dSample(); + void Box3dSample(); + void Cylinder3dSample(); + void Revolution3dSample(); + void TopologyIterator3dSample(); + void TopologyExplorer3dSample(); + void AssessToCurve3dSample(); + void AssessToCompositeCurve3dSample(); + void AssessToSurface3dSample(); + void Common3dSample(); + void Cut3dSample(); + void Fuse3dSample(); + void Section3dSample(); + void Splitter3dSample(); + void Defeaturing3dSample(); + void Fillet3dSample(); + void Chamfer3dSample(); + void Offset3dSample(); + void Evolved3dSample(); + void Copy3dSample(); + void Transform3dSample(); + void ConvertToNurbs3dSample(); + void SewContiguousFaces3dSample(); + void CheckValidity3dSample(); + void ComputeLinearProperties3dSample(); + void ComputeSurfaceProperties3dSample(); + void ComputeVolumeProperties3dSample(); +}; + +#endif //TOPOLOGYSAMPLES_H diff --git a/samples/OCCTOverview/code/Triangulation.json b/samples/OCCTOverview/code/Triangulation.json new file mode 100644 index 0000000000..9c3a8c5eba --- /dev/null +++ b/samples/OCCTOverview/code/Triangulation.json @@ -0,0 +1,10 @@ +{ + "Triangulation": { + + "Create Triangulation": [{ + "text": "Triangulation on shape", + "function": "Triangulation3dSample", + "description": "" + }] + } +} diff --git a/samples/OCCTOverview/code/TriangulationSamples.cxx b/samples/OCCTOverview/code/TriangulationSamples.cxx new file mode 100644 index 0000000000..eff114e831 --- /dev/null +++ b/samples/OCCTOverview/code/TriangulationSamples.cxx @@ -0,0 +1,118 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TriangulationSamples.h" + +#include "MakeBottle.h" + +#include <AIS_Shape.hxx> +#include <AIS_Triangulation.hxx> +#include <BRepMesh_IncrementalMesh.hxx> +#include <BRep_Tool.hxx> +#include <BRep_Builder.hxx> +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <Poly_Triangulation.hxx> +#include <TopExp_Explorer.hxx> +#include <TopoDS.hxx> +#include <TopoDS_Compound.hxx> +#include <TopoDS_Edge.hxx> +#include <TopoDS_Face.hxx> +#include <TopoDS_Shape.hxx> + +void TriangulationSamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "Triangulation3dSample") + { + Triangulation3dSample(); + } + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void TriangulationSamples::Triangulation3dSample() +{ + TopoDS_Shape aBottle = MakeBottle(50, 70, 30); + BRepMesh_IncrementalMesh(aBottle, 1); + + BRep_Builder aBuilder; + TopoDS_Compound aCompound; + aBuilder.MakeCompound(aCompound); + + Standard_Integer aNbTriangles(0); + for (TopExp_Explorer anExplorer(aBottle, TopAbs_FACE); anExplorer.More(); anExplorer.Next()) + { + TopoDS_Face aFace = TopoDS::Face(anExplorer.Current()); + TopLoc_Location aLocation; + Handle(Poly_Triangulation) aTriangulation = BRep_Tool::Triangulation(aFace, aLocation); + + TColgp_Array1OfPnt aTriangNodes(1, (aTriangulation->NbNodes())); + aTriangNodes = aTriangulation->Nodes(); + Poly_Array1OfTriangle aTriangles(1, aTriangulation->NbTriangles()); + aTriangles = aTriangulation->Triangles(); + + for (Standard_Integer i = 1; i <= (aTriangulation->NbTriangles()); i++) + { + Poly_Triangle trian = aTriangles.Value(i); + Standard_Integer index1, index2, index3, M = 0, N = 0; + trian.Get(index1, index2, index3); + + for (Standard_Integer j = 1; j <= 3; j++) + { + switch (j) + { + case 1: + M = index1; + N = index2; + break; + case 2: + N = index3; + break; + case 3: + M = index2; + } + + BRepBuilderAPI_MakeEdge anEdgeMaker(aTriangNodes.Value(M), aTriangNodes.Value(N)); + if (anEdgeMaker.IsDone()) + { + aBuilder.Add(aCompound, anEdgeMaker.Edge()); + } + } + } + Handle(AIS_Triangulation) anAisTriangulation = new AIS_Triangulation(aTriangulation); + aNbTriangles += aTriangulation->NbTriangles(); + myObject3d.Append(anAisTriangulation); + } + + Handle(AIS_Shape) anAisCompound = new AIS_Shape(aCompound); + myObject3d.Append(anAisCompound); + + Handle(AIS_Shape) AISBottle = new AIS_Shape(aBottle); + myObject3d.Append(AISBottle); + + myResult << "Compute the triangulation on a shape: " << aNbTriangles; +} diff --git a/samples/OCCTOverview/code/TriangulationSamples.h b/samples/OCCTOverview/code/TriangulationSamples.h new file mode 100644 index 0000000000..aaab1fc070 --- /dev/null +++ b/samples/OCCTOverview/code/TriangulationSamples.h @@ -0,0 +1,49 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef TRIANGULATIONSAMPLES_H +#define TRIANGULATIONSAMPLES_H + +#include "BaseSample.h" + +//! Implements Triangulation sample +class TriangulationSamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(TriangulationSamples, BaseSample) +public: + + TriangulationSamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample (theSampleSourcePath, theContext) + { + // + } + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + // One function for every sample + void Triangulation3dSample(); + +}; + +#endif //TRIANGULATIONSAMPLES_H diff --git a/samples/OCCTOverview/code/Viewer2d.json b/samples/OCCTOverview/code/Viewer2d.json new file mode 100644 index 0000000000..f5d3a5c3d3 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer2d.json @@ -0,0 +1,58 @@ +{ + "Viewer 2D": { + "Labels": [{ + "text": "Text", + "function": "TextView2dSample", + "description": "" + }, + { + "text": "Marker", + "function": "MarkerView2dSample", + "description": "" + }, + { + "text": "Fill Area", + "function": "FillAreaView2dSample", + "description": "" + }, + { + "text": "Loop on face", + "function": "LoopOnFaceView2dSample", + "description": "" + } + ], + + "Grids": [{ + "text": "Rectagular Lines", + "function": "RectagularLineGrid2dSample", + "description": "" + }, + { + "text": "Rectagular Points", + "function": "RectagularPointGrid2dSample", + "description": "" + }, + { + "text": "Circular Lines", + "function": "CircularLineGrid2dSample", + "description": "" + }, + { + "text": "Circular Points", + "function": "CircularPointGrid2dSample", + "description": "" + }, + { + "text": "Clear", + "function": "ClearGrid2dSample", + "description": "" + } + ], + + "Image": [{ + "text": "Backgroung Image", + "function": "BackgroungImage2dSample", + "description": "" + }] + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/Viewer2dSamples.cxx b/samples/OCCTOverview/code/Viewer2dSamples.cxx new file mode 100644 index 0000000000..ece0317601 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer2dSamples.cxx @@ -0,0 +1,282 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Viewer2dSamples.h" + +#include "Sample2D_Markers.h" +#include "Sample2D_Face.h" +#include "Sample2D_Image.h" + +#include <AIS_ColoredShape.hxx> +#include <AIS_TextLabel.hxx> +#include <BRepBuilderAPI_MakeEdge.hxx> +#include <BRepBuilderAPI_MakeWire.hxx> +#include <BRepBuilderAPI_MakeFace.hxx> +#include <TopoDS_Edge.hxx> +#include <TopoDS_Face.hxx> +#include <TopoDS_Wire.hxx> +#include <Quantity_NameOfColor.hxx> + +void Viewer2dSamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "TextView2dSample") + TextView2dSample(); + else if (theSampleName == "MarkerView2dSample") + MarkerView2dSample(); + else if (theSampleName == "FillAreaView2dSample") + FillAreaView2dSample(); + else if (theSampleName == "LoopOnFaceView2dSample") + LoopOnFaceView2dSample(); + else if (theSampleName == "RectagularLineGrid2dSample") + RectagularLineGrid2dSample(); + else if (theSampleName == "RectagularPointGrid2dSample") + RectagularPointGrid2dSample(); + else if (theSampleName == "CircularLineGrid2dSample") + CircularLineGrid2dSample(); + else if (theSampleName == "CircularPointGrid2dSample") + CircularPointGrid2dSample(); + else if (theSampleName == "ClearGrid2dSample") + ClearGrid2dSample(); + else if (theSampleName == "BackgroungImage2dSample") + BackgroungImage2dSample(); + else { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void Viewer2dSamples::ClearExtra() +{ + myContext->RemoveAll(Standard_True); + myViewer->DeactivateGrid(); +} + +void Viewer2dSamples::TextView2dSample() +{ + Standard_Integer aColor = Quantity_NameOfColor::Quantity_NOC_MATRABLUE; + for (Standard_Integer j = 15; j <= 20; j++) + { + Handle(AIS_TextLabel) aText = new AIS_TextLabel(); + aText->SetText(TCollection_AsciiString("font 0 scale ") + (j / 20.0)); + aText->SetPosition(gp_Pnt(0.0, 15.0 * (j - 15.0), 0.0)); + aText->SetAngle(30.0 * M_PI / 180.0); + aText->SetColor(Quantity_NameOfColor(aColor++)); + aText->SetFontAspect(Font_FA_Regular); + aText->SetFont("Courier"); + aText->SetHeight(j); + aText->SetHJustification(Graphic3d_HTA_LEFT); + aText->SetVJustification(Graphic3d_VTA_BOTTOM); + aText->SetZoomable(Standard_False); + myObject2d.Append(aText); + } + + for (Standard_Real j = 10; j <= 15; j++) + { + Handle(AIS_TextLabel) aText = new AIS_TextLabel(); + aText->SetText(TCollection_AsciiString("font 1 scale ") + (j / 10.0)); + aText->SetPosition(gp_Pnt(80.0, 15.0 * (j - 10.0), 0.0)); + aText->SetAngle(0.0); + aText->SetColor(Quantity_NameOfColor(aColor++)); + aText->SetFontAspect(Font_FA_BoldItalic); + aText->SetFont("Cambria"); + aText->SetHeight(j * 2); + aText->SetHJustification(Graphic3d_HTA_LEFT); + aText->SetVJustification(Graphic3d_VTA_BOTTOM); + aText->SetZoomable(Standard_False); + myObject2d.Append(aText); + } + + aColor = Quantity_NOC_MATRABLUE; + for (Standard_Real j = 5; j <= 10; j++) + { + Handle(AIS_TextLabel) aText = new AIS_TextLabel(); + aText->SetText(TCollection_AsciiString("font 2 scale ") + (j / 10.0)); + aText->SetPosition(gp_Pnt(140.0, 15.0 * (j - 5.0), 0.0)); + aText->SetAngle(0.0); + aText->SetColor(Quantity_NameOfColor(aColor++)); + aText->SetFontAspect(Font_FA_Bold); + aText->SetFont("Arial"); + aText->SetHeight(j * 2); + aText->SetHJustification(Graphic3d_HTA_LEFT); + aText->SetVJustification(Graphic3d_VTA_BOTTOM); + aText->SetZoomable(Standard_False); + myObject2d.Append(aText); + } + for (Standard_Real j = 10; j <= 15; j++) + { + Handle(AIS_TextLabel) aText = new AIS_TextLabel(); + aText->SetText(TCollection_AsciiString("font 3 scale ") + (j / 10.0)); + aText->SetPosition(gp_Pnt(200.0, 15.0 * (j - 10.0), 0.0)); + aText->SetAngle(0.0); + aText->SetColor(Quantity_NameOfColor(aColor++)); + aText->SetFontAspect(Font_FA_Italic); + aText->SetFont("Georgia"); + aText->SetHeight(j * 2); + aText->SetHJustification(Graphic3d_HTA_LEFT); + aText->SetVJustification(Graphic3d_VTA_BOTTOM); + aText->SetZoomable(Standard_False); + myObject2d.Append(aText); + } +} + +void Viewer2dSamples::MarkerView2dSample() +{ + // generic Markers + Standard_Integer aColor = 20; + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 5, 5 * i, Aspect_TOM_POINT, Quantity_NOC_YELLOW, 2.0); + myObject2d.Append(aMarker); + } + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 10, 5 * i, Aspect_TOM_O, (Quantity_NameOfColor)(aColor++)); + myObject2d.Append(aMarker); + } + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 15, 5 * i, Aspect_TOM_O_PLUS, (Quantity_NameOfColor)(aColor++)); + myObject2d.Append(aMarker); + } + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 20, 5 * i, Aspect_TOM_RING1, (Quantity_NameOfColor)(aColor++)); + myObject2d.Append(aMarker); + } + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 25, 5 * i, Aspect_TOM_STAR, (Quantity_NameOfColor)(aColor++)); + myObject2d.Append(aMarker); + } + for (int i = 1; i <= 2; i++) + { + Handle(Sample2D_Markers) aMarker = new Sample2D_Markers(10 + 30, 5 * i, Aspect_TOM_O_X, (Quantity_NameOfColor)(aColor++)); + myObject2d.Append(aMarker); + } +} + +void Viewer2dSamples::FillAreaView2dSample() +{ + for (int i = 0; i <= 13; ++i) + { + for (int j = 0; j <= 5; ++j) + { + // set of rectangles here + TopoDS_Edge E1 = BRepBuilderAPI_MakeEdge(gp_Pnt(10 * i, 10 * j, 0.), gp_Pnt(10 * i + 7, 10 * j, 0.)); + TopoDS_Edge E2 = BRepBuilderAPI_MakeEdge(gp_Pnt(10 * i + 7, 10 * j, 0.), gp_Pnt(10 * i + 7, 10 * j + 5, 0.)); + TopoDS_Edge E3 = BRepBuilderAPI_MakeEdge(gp_Pnt(10 * i + 7, 10 * j + 5, 0.), gp_Pnt(10 * i, 10 * j + 5, 0.)); + TopoDS_Edge E4 = BRepBuilderAPI_MakeEdge(gp_Pnt(10 * i, 10 * j + 5, 0.), gp_Pnt(10 * i, 10 * j, 0.)); + TopoDS_Wire W = BRepBuilderAPI_MakeWire(E1, E2, E3, E4); + TopoDS_Face F = BRepBuilderAPI_MakeFace(W); + Handle(AIS_Shape) aRect = new AIS_Shape(F); + // set attributes of boundaries + Handle(Prs3d_Drawer) aDrawer = new Prs3d_Drawer(); + Handle(Prs3d_LineAspect) aLineAttrib = new Prs3d_LineAspect (Quantity_NOC_YELLOW, + (Aspect_TypeOfLine)(Aspect_TOL_SOLID + j), 1); + aDrawer->SetFaceBoundaryAspect(aLineAttrib); + aDrawer->SetFaceBoundaryDraw(Standard_True); + aRect->SetAttributes(aDrawer); + + myContext->SetDisplayMode(aRect, 1, Standard_False); + myContext->SetColor(aRect, (Quantity_NameOfColor)(Quantity_NOC_CADETBLUE + 2 * i), Standard_False); + myContext->SetMaterial(aRect, Graphic3d_NOM_PLASTIC, Standard_False); + myObject2d.Append(aRect); + + } + } +} + +void Viewer2dSamples::LoopOnFaceView2dSample() +{ + // Make a flat rectangular face on XY plane. + gp_Pln aPln(gp::XOY()); + TopoDS_Face aFaceRect = BRepBuilderAPI_MakeFace(aPln, -10.0, +10.0, -20.0, +20.0); + + Handle(AIS_ColoredShape) anAisFaceRect = new AIS_ColoredShape(aFaceRect); + anAisFaceRect->SetColor(Quantity_Color(Quantity_NOC_RED)); + myObject2d.Append(anAisFaceRect); + + TopoDS_Shape aFaceShape; + Handle(Sample2D_Face) anAISFace = new Sample2D_Face(aFaceRect); + myObject2d.Append(anAISFace); +} + +void Viewer2dSamples::RectagularLineGrid2dSample() +{ + Handle(Graphic3d_AspectMarker3d) aGridAspect = new Graphic3d_AspectMarker3d(Aspect_TOM_RING1, Quantity_NOC_WHITE, 2); + myViewer->SetGridEcho(aGridAspect); + Standard_Integer aWidth = 0, aHeight = 0, anOffset = 0; + myView->Window()->Size(aWidth, aHeight); + myViewer->SetRectangularGridGraphicValues(aWidth, aHeight, anOffset); + myViewer->ActivateGrid(Aspect_GT_Rectangular, Aspect_GDM_Lines); + myViewer->Redraw(); +} + +void Viewer2dSamples::RectagularPointGrid2dSample() +{ + Handle(Graphic3d_AspectMarker3d) aGridAspect = new Graphic3d_AspectMarker3d(Aspect_TOM_RING1, Quantity_NOC_WHITE, 2); + myViewer->SetGridEcho(aGridAspect); + Standard_Integer aWidth = 0, aHeight = 0, anOffset = 0; + myView->Window()->Size(aWidth, aHeight); + myViewer->SetRectangularGridGraphicValues(aWidth, aHeight, anOffset); + myViewer->ActivateGrid(Aspect_GT_Rectangular, Aspect_GDM_Points); + myViewer->Redraw(); +} + +void Viewer2dSamples::CircularLineGrid2dSample() +{ + Handle(Graphic3d_AspectMarker3d) aGridAspect = new Graphic3d_AspectMarker3d(Aspect_TOM_RING1, Quantity_NOC_WHITE, 2); + myViewer->SetGridEcho(aGridAspect); + Standard_Integer aWidth = 0, aHeight = 0, anOffset = 0; + myView->Window()->Size(aWidth, aHeight); + myViewer->SetRectangularGridGraphicValues(aWidth, aHeight, anOffset); + myViewer->ActivateGrid(Aspect_GT_Circular, Aspect_GDM_Lines); + myViewer->Redraw(); +} + +void Viewer2dSamples::CircularPointGrid2dSample() +{ + Handle(Graphic3d_AspectMarker3d) aGridAspect = new Graphic3d_AspectMarker3d(Aspect_TOM_RING1, Quantity_NOC_WHITE, 2); + myViewer->SetGridEcho(aGridAspect); + Standard_Integer aWidth = 0, aHeight = 0, anOffset = 0; + myView->Window()->Size(aWidth, aHeight); + myViewer->SetRectangularGridGraphicValues(aWidth, aHeight, anOffset); + myViewer->ActivateGrid(Aspect_GT_Circular, Aspect_GDM_Points); + myViewer->Redraw(); +} + +void Viewer2dSamples::ClearGrid2dSample() +{ + myViewer->DeactivateGrid(); + myViewer->Redraw(); +} + +void Viewer2dSamples::BackgroungImage2dSample() +{ + Handle(Sample2D_Image) anImage = new Sample2D_Image(myFileName); + anImage->SetCoord(40, 50); + anImage->SetScale(1.0); + myObject2d.Append(anImage); +} diff --git a/samples/OCCTOverview/code/Viewer2dSamples.h b/samples/OCCTOverview/code/Viewer2dSamples.h new file mode 100644 index 0000000000..66deb43b70 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer2dSamples.h @@ -0,0 +1,76 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef VIEWER2DSAMPLES_H +#define VIEWER2DSAMPLES_H + +#include "BaseSample.h" + +#include <AIS_InteractiveContext.hxx> +#include <V3d_View.hxx> + +//! Implements viewer 2D samples. +class Viewer2dSamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(Viewer2dSamples, BaseSample) +public: + + Viewer2dSamples(const TCollection_AsciiString& theSampleSourcePath, + const Handle(V3d_View)& theView, + const Handle(V3d_Viewer)& theViewer, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample (theSampleSourcePath, theContext), + myView (theView), + myViewer (theViewer) + {} + + void SetFileName (const TCollection_AsciiString& theFileName) { myFileName = theFileName; } + void ClearExtra(); + + static Standard_Boolean IsFileSample (const TCollection_AsciiString& theSampleName) { return theSampleName == "BackgroungImage2dSample"; } + static Standard_Boolean IsShadedSample(const TCollection_AsciiString& theSampleName) { return theSampleName == "BackgroungImage2dSample"; } + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + + // One function for every sample + void TextView2dSample(); + void MarkerView2dSample(); + void FillAreaView2dSample(); + void LoopOnFaceView2dSample(); + void RectagularLineGrid2dSample(); + void RectagularPointGrid2dSample(); + void CircularLineGrid2dSample(); + void CircularPointGrid2dSample(); + void ClearGrid2dSample(); + void BackgroungImage2dSample(); + +private: + + TCollection_AsciiString myFileName; + Handle(V3d_View) myView; + Handle(V3d_Viewer) myViewer; + +}; + +#endif // VIEWER2DSAMPLES_H diff --git a/samples/OCCTOverview/code/Viewer3d.json b/samples/OCCTOverview/code/Viewer3d.json new file mode 100644 index 0000000000..19c2361b33 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer3d.json @@ -0,0 +1,106 @@ +{ + "Viewer 3D": { + "Light source": [{ + "text": "Spot", + "function": "SpotLight3dSample", + "description": "" + }, + { + "text": "Positional", + "function": "PositionalLight3dSample", + "description": "" + }, + { + "text": "Directional", + "function": "DirectionalLight3dSample", + "description": "" + }, + { + "text": "Ambient", + "function": "AmbientLight3dSample", + "description": "" + }, + { + "text": "Clear", + "function": "ClearLight3dSample", + "description": "" + } + ], + + "Selection mode": [{ + "text": "Vertices", + "function": "VerticesSelect3dSample", + "description": "" + }, + { + "text": "Edges", + "function": "EdgesSelect3dSample", + "description": "" + }, + { + "text": "Faces", + "function": "FacesSelect3dSample", + "description": "" + }, + { + "text": "Neutral point", + "function": "NeutralPointSelect3dSample", + "description": "" + } + ], + + "Shape presentation": [ + { + "text": "WireFrame", + "function": "WireFramePresentation3dSample", + "description": "" + }, + { + "text": "Shading", + "function": "ShadingPresentation3dSample", + "description": "" + }, + { + "text": "Set color to red", + "function": "RedColorPresentation3dSample", + "description": "" + }, + { + "text": "Set color to gray", + "function": "GrayColorPresentation3dSample", + "description": "" + }, + { + "text": "Set plastic material", + "function": "PlasticPresentation3dSample", + "description": "" + }, + { + "text": "Set bronze material", + "function": "BronzePresentation3dSample", + "description": "" + }, + { + "text": "Set opaque", + "function": "OpaquePresentation3dSample", + "description": "" + }, + { + "text": "Set half transparency", + "function": "HalfTransparencyPresentation3dSample", + "description": "" + } + ], + "OpenGL VBO mode": [{ + "text": "Vertex Buffer Object mode ON", + "function": "VboOn3dSample", + "description": "" + }, + { + "text": "Vertex Buffer Object mode OFF", + "function": "VboOff3dSample", + "description": "" + } + ] + } +} \ No newline at end of file diff --git a/samples/OCCTOverview/code/Viewer3dSamples.cxx b/samples/OCCTOverview/code/Viewer3dSamples.cxx new file mode 100644 index 0000000000..ed67349180 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer3dSamples.cxx @@ -0,0 +1,312 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Viewer3dSamples.h" + +#include "MakeBottle.h" + +#include <AIS_Shape.hxx> +#include <AIS_ViewCube.hxx> +#include <OpenGl_GraphicDriver.hxx> +#include <V3d_SpotLight.hxx> +#include <V3d_PositionalLight.hxx> +#include <V3d_DirectionalLight.hxx> +#include <V3d_AmbientLight.hxx> + +void Viewer3dSamples::ExecuteSample (const TCollection_AsciiString& theSampleName) +{ + Standard_Boolean anIsSamplePresent = Standard_True; + FindSourceCode(theSampleName); + if (theSampleName == "SpotLight3dSample") + SpotLight3dSample(); + else if (theSampleName == "PositionalLight3dSample") + PositionalLight3dSample(); + else if (theSampleName == "DirectionalLight3dSample") + DirectionalLight3dSample(); + else if (theSampleName == "AmbientLight3dSample") + AmbientLight3dSample(); + else if (theSampleName == "ClearLight3dSample") + ClearLight3dSample(); + else if (theSampleName == "VerticesSelect3dSample") + VerticesSelect3dSample(); + else if (theSampleName == "EdgesSelect3dSample") + EdgesSelect3dSample(); + else if (theSampleName == "FacesSelect3dSample") + FacesSelect3dSample(); + else if (theSampleName == "NeutralPointSelect3dSample") + NeutralPointSelect3dSample(); + else if (theSampleName == "WireFramePresentation3dSample") + WireFramePresentation3dSample(); + else if (theSampleName == "ShadingPresentation3dSample") + ShadingPresentation3dSample(); + else if (theSampleName == "RedColorPresentation3dSample") + RedColorPresentation3dSample(); + else if (theSampleName == "GrayColorPresentation3dSample") + GrayColorPresentation3dSample(); + else if (theSampleName == "PlasticPresentation3dSample") + PlasticPresentation3dSample(); + else if (theSampleName == "BronzePresentation3dSample") + BronzePresentation3dSample(); + else if (theSampleName == "OpaquePresentation3dSample") + OpaquePresentation3dSample(); + else if (theSampleName == "HalfTransparencyPresentation3dSample") + HalfTransparencyPresentation3dSample(); + else if (theSampleName == "VboOn3dSample") + VboOn3dSample(); + else if (theSampleName == "VboOff3dSample") + VboOff3dSample(); + else + { + myResult << "No function found: " << theSampleName; + myCode += TCollection_AsciiString("No function found: ") + theSampleName; + anIsSamplePresent = Standard_False; + } + myIsProcessed = anIsSamplePresent; +} + +void Viewer3dSamples::AppendBottle() +{ + TopoDS_Shape aBottle = MakeBottle(50, 70, 30); + Handle(AIS_InteractiveObject) aShape = new AIS_Shape(aBottle); + myObject3d.Append(aShape); + Handle(AIS_ViewCube) aViewCube = new AIS_ViewCube(); + myObject3d.Append(aViewCube); + myResult << "A bottle shape was created." << std::endl; +} + +void Viewer3dSamples::ClearExtra() +{ + NeutralPointSelect3dSample(); + VboOff3dSample(); + ClearLight3dSample(); + // Delete Lights + V3d_ListOfLight aLights; + for (V3d_ListOfLightIterator anIter = myView->Viewer()->DefinedLightIterator(); anIter.More(); anIter.Next()) + { + aLights.Append(anIter.Value()); + } + + for (V3d_ListOfLightIterator aLightIter (aLights); aLightIter.More(); aLightIter.Next()) + { + myView->Viewer()->DelLight (aLightIter.Value()); + } + myView->Viewer()->SetDefaultLights(); // Setting the default lights on + myView->Update(); + + myContext->RemoveAll (Standard_True); +} + +void Viewer3dSamples::SpotLight3dSample() +{ + // Spot light source creation + Handle(V3d_SpotLight) aSpotLight = new V3d_SpotLight(gp_Pnt(100.0, 0.0, 0.0), gp_Dir(-1.0, 0.0, 0.0), Quantity_NOC_RED); + aSpotLight->SetIntensity(5000); + myView->SetLightOn(aSpotLight); +} + +void Viewer3dSamples::PositionalLight3dSample() +{ + Handle(V3d_PositionalLight) aPositionalLight = new V3d_PositionalLight(gp_Pnt(0.0, -100.0, 5.0), Quantity_NOC_GREEN); + aPositionalLight->SetAttenuation(1, 0); + myView->SetLightOn(aPositionalLight); +} + +void Viewer3dSamples::DirectionalLight3dSample() +{ + Handle(V3d_DirectionalLight) aDirectionalLight = new V3d_DirectionalLight(gp_Dir(-1.0, 0.0, -1.0), Quantity_NOC_BLUE1); + myView->SetLightOn(aDirectionalLight); +} + +void Viewer3dSamples::AmbientLight3dSample() +{ + Handle(V3d_AmbientLight) aAmbientLight = new V3d_AmbientLight(Quantity_NOC_MAGENTA1); + myView->SetLightOn(aAmbientLight); +} + +void Viewer3dSamples::ClearLight3dSample() +{ + // Setting Off all viewer active lights + V3d_ListOfLight aLights; + for (V3d_ListOfLightIterator anIter = myView->Viewer()->ActiveLightIterator(); anIter.More(); anIter.Next()) + { + aLights.Append(anIter.Value()); + } + + for (V3d_ListOfLightIterator aLightIter (aLights); aLightIter.More(); aLightIter.Next()) + { + myView->Viewer()->SetLightOff (aLightIter.Value()); + } + // Setting Off all view active lights + aLights.Clear(); + for (V3d_ListOfLightIterator anIter = myView->ActiveLightIterator(); anIter.More(); anIter.Next()) + { + aLights.Append(anIter.Value()); + } + + for (V3d_ListOfLightIterator aLightIter (aLights); aLightIter.More(); aLightIter.Next()) + { + myView->SetLightOff (aLightIter.Value()); + } + myView->Viewer()->SetDefaultLights(); // Setting the default lights on + myView->Update(); +} + +void Viewer3dSamples::VerticesSelect3dSample() +{ + myContext->Deactivate(); + myContext->Activate(AIS_Shape::SelectionMode(TopAbs_VERTEX)); +} + +void Viewer3dSamples::EdgesSelect3dSample() +{ + myContext->Deactivate(); + myContext->Activate(AIS_Shape::SelectionMode(TopAbs_EDGE)); +} + +void Viewer3dSamples::FacesSelect3dSample() +{ + myContext->Deactivate(); + myContext->Activate(AIS_Shape::SelectionMode(TopAbs_FACE)); +} + +void Viewer3dSamples::NeutralPointSelect3dSample() +{ + myContext->Deactivate(); + myContext->Activate(0); +} + +void Viewer3dSamples::WireFramePresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetDisplayMode(anAisObject, 0, false); // set wireframe + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::ShadingPresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetDisplayMode(anAisObject, 1, false); // set shading + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::RedColorPresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + Quantity_Color aShapeColor; + myContext->Color(anAisObject, aShapeColor); + myResult << "A Current shape color: Red = " << aShapeColor.Red() + << " Green = " << aShapeColor.Green() << " Blue = " << aShapeColor.Blue() << std::endl; + aShapeColor.SetValues(0.8, 0.1, 0.1, Quantity_TOC_RGB); + myContext->SetColor(anAisObject, aShapeColor, Standard_False); + myResult << "A New shape color: Red = " << aShapeColor.Red() + << " Green = " << aShapeColor.Green() << " Blue = " << aShapeColor.Blue() << std::endl; + } +} + +void Viewer3dSamples::GrayColorPresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + Quantity_Color aShapeColor; + myContext->Color(anAisObject, aShapeColor); + myResult << "A Current shape color: Hue = " << aShapeColor.Hue() + << " Light = " << aShapeColor.Light() << " Saturation = " << aShapeColor.Saturation() << std::endl; + aShapeColor.SetValues(0.0, 0.3, 0.1, Quantity_TOC_HLS); + myContext->SetColor(anAisObject, aShapeColor, Standard_False); + myResult << "A New shape color: Hue = " << aShapeColor.Hue() + << " Light = " << aShapeColor.Light() << " Saturation = " << aShapeColor.Saturation() << std::endl; + } +} + +void Viewer3dSamples::PlasticPresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + Graphic3d_NameOfMaterial aMaterial = Graphic3d_NOM_PLASTIC; + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetMaterial(anAisObject, aMaterial, Standard_False); + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::BronzePresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + Graphic3d_NameOfMaterial aMaterial = Graphic3d_NOM_BRONZE; + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetMaterial(anAisObject, aMaterial, Standard_False); + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::OpaquePresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetTransparency(anAisObject, 0.0, Standard_False); + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::HalfTransparencyPresentation3dSample() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetTransparency(anAisObject, 0.5, Standard_False); + } + myContext->UpdateCurrentViewer(); +} + +void Viewer3dSamples::VboOn3dSample() +{ + if (Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast(myContext->CurrentViewer()->Driver())) + { + aDriver->ChangeOptions().vboDisable = Standard_False; + } +} + +void Viewer3dSamples::VboOff3dSample() +{ + if (Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast(myContext->CurrentViewer()->Driver())) + { + aDriver->ChangeOptions().vboDisable = Standard_True; + } +} diff --git a/samples/OCCTOverview/code/Viewer3dSamples.h b/samples/OCCTOverview/code/Viewer3dSamples.h new file mode 100644 index 0000000000..1691736b30 --- /dev/null +++ b/samples/OCCTOverview/code/Viewer3dSamples.h @@ -0,0 +1,78 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef VIEWER3DSAMPLES_H +#define VIEWER3DSAMPLES_H + +#include "BaseSample.h" + +#include <AIS_InteractiveContext.hxx> +#include <V3d_View.hxx> + +//! Implements viewer 3D samples. +class Viewer3dSamples : public BaseSample +{ + DEFINE_STANDARD_RTTI_INLINE(Viewer3dSamples, BaseSample) +public: + + Viewer3dSamples (const TCollection_AsciiString& theSampleSourcePath, + const Handle(V3d_View)& theView, + const Handle(AIS_InteractiveContext)& theContext) + : BaseSample (theSampleSourcePath, theContext), + myView (theView) + {} + + void AppendBottle(); + void ClearExtra(); + +protected: + virtual void ExecuteSample (const TCollection_AsciiString& theSampleName) Standard_OVERRIDE; + +private: + + // One function for every sample + void SpotLight3dSample(); + void PositionalLight3dSample(); + void DirectionalLight3dSample(); + void AmbientLight3dSample(); + void ClearLight3dSample(); + void VerticesSelect3dSample(); + void EdgesSelect3dSample(); + void FacesSelect3dSample(); + void NeutralPointSelect3dSample(); + void WireFramePresentation3dSample(); + void ShadingPresentation3dSample(); + void RedColorPresentation3dSample(); + void GrayColorPresentation3dSample(); + void PlasticPresentation3dSample(); + void BronzePresentation3dSample(); + void OpaquePresentation3dSample(); + void HalfTransparencyPresentation3dSample(); + void VboOn3dSample(); + void VboOff3dSample(); + +private: + + Handle(V3d_View) myView; + +}; + +#endif //VIEWER3DSAMPLES_H diff --git a/samples/qt/IESample/.gitignore b/samples/qt/IESample/.gitignore new file mode 100644 index 0000000000..7ac6e6bc69 --- /dev/null +++ b/samples/qt/IESample/.gitignore @@ -0,0 +1,7 @@ +/debug +/release +*.sln +*.vcxproj* +.qmake.stash +/custom.bat +/custom.sh diff --git a/samples/qt/IESample/custom.bat b/samples/qt/IESample/custom.bat deleted file mode 100644 index b5eea5240f..0000000000 --- a/samples/qt/IESample/custom.bat +++ /dev/null @@ -1,4 +0,0 @@ -@echo off -rem Define QTDIR variable - -set "QTDIR=" diff --git a/samples/qt/IESample/custom.bat.template b/samples/qt/IESample/custom.bat.template new file mode 100644 index 0000000000..dda84faa21 --- /dev/null +++ b/samples/qt/IESample/custom.bat.template @@ -0,0 +1,5 @@ +@echo off +rem Rename this file to custom.bat, +rem and define QTDIR variable. + +set "QTDIR=" diff --git a/samples/qt/IESample/custom.sh b/samples/qt/IESample/custom.sh deleted file mode 100755 index d9705989ff..0000000000 --- a/samples/qt/IESample/custom.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -#Define QTDIR variable - -export QTDIR="" diff --git a/samples/qt/IESample/custom.sh.template b/samples/qt/IESample/custom.sh.template new file mode 100644 index 0000000000..52571f097b --- /dev/null +++ b/samples/qt/IESample/custom.sh.template @@ -0,0 +1,5 @@ +#!/bin/bash +# Rename this file to custom.sh, +# and define QTDIR variable. + +export QTDIR="" diff --git a/samples/qt/IESample/env.bat b/samples/qt/IESample/env.bat index 3b7e3e4eb7..3e090cff49 100755 --- a/samples/qt/IESample/env.bat +++ b/samples/qt/IESample/env.bat @@ -1,8 +1,10 @@ @echo off -call "%~dp0..\..\..\env.bat" %1 %2 %3 +if exist "%~dp0custom.bat" ( + call "%~dp0custom.bat" %1 %2 %3 +) -call "custom.bat" %1 %2 %3 +call "%~dp0..\..\..\env.bat" %1 %2 %3 set "RES_DIR=%~dp0win%ARCH%\%VCVER%\res" set "CSF_ResourcesDefaults=%RES_DIR%" diff --git a/samples/qt/OCCTOverview/.gitignore b/samples/qt/OCCTOverview/.gitignore new file mode 100644 index 0000000000..7ac6e6bc69 --- /dev/null +++ b/samples/qt/OCCTOverview/.gitignore @@ -0,0 +1,7 @@ +/debug +/release +*.sln +*.vcxproj* +.qmake.stash +/custom.bat +/custom.sh diff --git a/samples/qt/OCCTOverview/CMakeLists.txt b/samples/qt/OCCTOverview/CMakeLists.txt new file mode 100644 index 0000000000..e9afaa4f65 --- /dev/null +++ b/samples/qt/OCCTOverview/CMakeLists.txt @@ -0,0 +1,8 @@ +project(OCCTOverview) + +OCCT_INCLUDE_CMAKE_FILE (adm/cmake/occt_toolkit_prepare_sample) +include_directories("${CMAKE_SOURCE_DIR}/${RELATIVE_DIR}/../OCCTOverview/code") +OCCT_INCLUDE_CMAKE_FILE (adm/cmake/occt_toolkit) +OCCT_INCLUDE_CMAKE_FILE (adm/cmake/occt_toolkit_prepare_sample) + +ADD_DEFINITIONS(-DNO_COMMONSAMPLE_EXPORTS -DNO_IESAMPLE_EXPORTS) diff --git a/samples/qt/OCCTOverview/EXTERNLIB b/samples/qt/OCCTOverview/EXTERNLIB new file mode 100644 index 0000000000..81f55c1328 --- /dev/null +++ b/samples/qt/OCCTOverview/EXTERNLIB @@ -0,0 +1,33 @@ +TKBRep +TKBin +TKBool +TKBO +TKCDF +TKFillet +TKG2d +TKG3d +TKGeomAlgo +TKGeomBase +TKernel +TKHLR +TKIGES +TKMath +TKMesh +TKOffset +TKOpenGl +TKPrim +TKService +TKShHealing +TKSTEP +TKSTEP209 +TKSTEPAttr +TKSTEPBase +TKSTL +TKTopAlgo +TKV3d +TKVRML +TKXSBase +TKLCAF +TKCAF +TKVCAF +TKXml diff --git a/samples/qt/OCCTOverview/FILES b/samples/qt/OCCTOverview/FILES new file mode 100644 index 0000000000..ca4f0e567b --- /dev/null +++ b/samples/qt/OCCTOverview/FILES @@ -0,0 +1,2 @@ +EXTERNLIB +PACKAGES diff --git a/samples/qt/OCCTOverview/OCCTOverview.pro b/samples/qt/OCCTOverview/OCCTOverview.pro new file mode 100644 index 0000000000..850d82476a --- /dev/null +++ b/samples/qt/OCCTOverview/OCCTOverview.pro @@ -0,0 +1,89 @@ +TEMPLATE = app +CONFIG += debug_and_release qt +CONFIG += lrelease +CONFIG += embed_translations +QT += widgets + +TARGET = OCCTOverview + +SAMPLESROOT = $$quote($$(CSF_OCCTSamplesPath)/qt) + +FREEIMAGE_DIR = $$quote($$(FREEIMAGE_DIR)) +TBB_DIR = $$quote($$(TBB_DIR)) + +HEADERS = ./src/*.h \ + $${SAMPLESROOT}/../OCCTOverview/code/*.h + +SOURCES = ./src/*.cxx \ + $${SAMPLESROOT}/../OCCTOverview/code/*.cxx + +RESOURCES += $${SAMPLESROOT}/../OCCTOverview/code/Samples.qrc +RESOURCES += ./src/OCCTOverview.qrc + +RES_DIR = $$quote($$(RES_DIR)) + +INCLUDEPATH += $$quote($$(CSF_SampleSources)) +INCLUDEPATH += $$quote($$(CSF_OCCTIncludePath)) \ + $${SAMPLESROOT}/../OCCTOverview/code + + +OCCT_DEFINES = $$(CSF_DEFINES) + +DEFINES = $$split(OCCT_DEFINES, ;) + +unix { + UNAME = $$system(uname -s) + LIBLIST = $$(LD_LIBRARY_PATH) + LIBPATHS = $$split(LIBLIST,":") + for(lib, LIBPATHS):LIBS += -L$${lib} + + CONFIG(debug, debug|release) { + DESTDIR = ./$$UNAME/bind + OBJECTS_DIR = ./$$UNAME/objd + MOC_DIR = ./$$UNAME/mocd + } else { + DESTDIR = ./$$UNAME/bin + OBJECTS_DIR = ./$$UNAME/obj + MOC_DIR = ./$$UNAME/moc + } + + MACOSX_USE_GLX = $$(MACOSX_USE_GLX) + + !macx | equals(MACOSX_USE_GLX, true): INCLUDEPATH += $$QMAKE_INCDIR_X11 $$QMAKE_INCDIR_OPENGL $$QMAKE_INCDIR_THREAD + equals(MACOSX_USE_GLX, true): DEFINES += MACOSX_USE_GLX + DEFINES += OCC_CONVERT_SIGNALS QT_NO_STL + !macx | equals(MACOSX_USE_GLX, true): LIBS += -L$$QMAKE_LIBDIR_X11 $$QMAKE_LIBS_X11 -L$$QMAKE_LIBDIR_OPENGL $$QMAKE_LIBS_OPENGL $$QMAKE_LIBS_THREAD + + QMAKE_CXXFLAGS += -std=gnu++11 +} + +win32 { + CONFIG(debug, debug|release) { + DEFINES += _DEBUG + DESTDIR = ./win$$(ARCH)/$$(VCVER)/bind + OBJECTS_DIR = ./win$$(ARCH)/$$(VCVER)/objd + MOC_DIR = ./win$$(ARCH)/$$(VCVER)/mocd + } else { + DEFINES += NDEBUG + DESTDIR = ./win$$(ARCH)/$$(VCVER)/bin + OBJECTS_DIR = ./win$$(ARCH)/$$(VCVER)/obj + MOC_DIR = ./win$$(ARCH)/$$(VCVER)/moc + } + LIBS = -L$$(QTDIR)/lib;$$(CSF_OCCTLibPath) + DEFINES += NO_COMMONSAMPLE_EXPORTS NO_IESAMPLE_EXPORTS +} + +LIBS += -lTKernel -lTKMath -lTKService -lTKV3d -lTKOpenGl \ + -lTKBRep -lTKIGES -lTKSTL -lTKVRML -lTKSTEP -lTKSTEPAttr -lTKSTEP209 \ + -lTKSTEPBase -lTKGeomBase -lTKGeomAlgo -lTKG3d -lTKG2d \ + -lTKXSBase -lTKShHealing -lTKHLR -lTKTopAlgo -lTKMesh -lTKPrim \ + -lTKCDF -lTKBool -lTKBO -lTKFillet -lTKOffset -lTKLCAF -lTKCAF -lTKVCAF \ + -lTKBin -lTKXml + +!exists($${RES_DIR}) { + win32 { + system(mkdir $${RES_DIR}) + } else { + system(mkdir -p $${RES_DIR}) + } +} diff --git a/samples/qt/OCCTOverview/OCCTOverview0.pro b/samples/qt/OCCTOverview/OCCTOverview0.pro new file mode 100644 index 0000000000..ec2948b973 --- /dev/null +++ b/samples/qt/OCCTOverview/OCCTOverview0.pro @@ -0,0 +1,5 @@ +TEMPLATE=subdirs + +SUBDIRS=OCCTOverview0 + +OCCTOverview0.file=OCCTOverview.pro diff --git a/samples/qt/OCCTOverview/PACKAGES b/samples/qt/OCCTOverview/PACKAGES new file mode 100644 index 0000000000..0d40a31f87 --- /dev/null +++ b/samples/qt/OCCTOverview/PACKAGES @@ -0,0 +1,2 @@ +OCCTOverview/src +/../OCCTOverview/code diff --git a/samples/qt/OCCTOverview/ReadMe.md b/samples/qt/OCCTOverview/ReadMe.md new file mode 100644 index 0000000000..99fae6050b --- /dev/null +++ b/samples/qt/OCCTOverview/ReadMe.md @@ -0,0 +1,58 @@ +Qt OCCT Overview samples {#samples_qt_overview} +========== + +1. Contents +----------------------- + +The directory <i> samples/qt/OCCTOverview </i> contains the folders and files of the Qt OCCT Overview application: + +* Files **OCCTOverview.pro** and **OCCTOverview0.pro** are Qt project files. +* File **genproj.bat** to denerate MS Visual Studio project. +* File **msvc.bat** to run MS Visual Studio project. +* File **make.sh** to build of the application on Linux. +* Files **run.bat** and **run.sh** to runn the application. +* Files **env.bat** and **custom.bat** are called from *genproj.bat*, *msvc.bat*, *run.bat*. + File *custom.bat* should be defined by user to provide paths to QT directory and OCCT installation directory (see *custom.bat.template*). +* **src** and **res** directories provide source and resources files. + +The directory <i> samples/OCCTOverview/code </i> contains the source code of samples. + +2. How to build Qt OCCT Overview application +--------------------------------- + +* Edit custom.bat file. It is necessary to define following variables: + * **QTDIR** path to where Qt is installed + * **CASROOT** path to where Open CASCADE binaries are installed. + +* Build the application: + + * On Windows: + * Generate project files: `> genproj.bat vc141 win64 Debug` + * Launch MS Visual Studio: `> msvc.bat vc141 win64 Debug` + * Build the application using MS Visual Studio. + + * On Linux: Launch building of the application by make.sh script + +3. Running the application +-------------------------- + +* On Windows: +~~~~ + > run.bat vc141 win64 Debug +~~~~ + +* On Linux: +~~~~ + > run.sh +~~~~ + +4. How to use the OCCT Overview application: +--------------------------------- + +* To select a samples categogy use the *Category* menu. +* To run concrete sample using the menu to the right of the category menu. +* See on a souce code in the *Sample code* window. Сopy the code if needed. +* See on a sample output in the *Output* window if it exist. +* Zoom, pan and rotate a geometry in the mail window using the mouse. + +See hints how to use the mouse in down hints panel. diff --git a/samples/qt/OCCTOverview/custom.bat.template b/samples/qt/OCCTOverview/custom.bat.template new file mode 100644 index 0000000000..49dccac5e8 --- /dev/null +++ b/samples/qt/OCCTOverview/custom.bat.template @@ -0,0 +1,7 @@ +@echo off +rem Rename this file to custom.bat, +rem define QTDIR variable - path to Qt directory +rem and CASROOT variable - path to Open CASCADE installation directory. + +set "CASROOT=%~dp0../../.." +set "QTDIR=" diff --git a/samples/qt/OCCTOverview/custom.sh.template b/samples/qt/OCCTOverview/custom.sh.template new file mode 100644 index 0000000000..756d3dda9d --- /dev/null +++ b/samples/qt/OCCTOverview/custom.sh.template @@ -0,0 +1,9 @@ +#!/bin/bash +# Rename this file to custom.sh, +# define QTDIR variable - path to QT directory +# and CASROOT variable - path to CasCade installation directory. + +aScriptPath=${BASH_SOURCE%/*} + +export CASROOT=${aScriptPath}/../../.. +export QTDIR= diff --git a/samples/qt/OCCTOverview/env.bat b/samples/qt/OCCTOverview/env.bat new file mode 100644 index 0000000000..008277ad0d --- /dev/null +++ b/samples/qt/OCCTOverview/env.bat @@ -0,0 +1,29 @@ +@echo off + +if exist "%~dp0custom.bat" ( + call "%~dp0custom.bat" %1 %2 %3 +) + +call "%CASROOT%\env.bat" %1 %2 %3 + +if /I ["%1"] == ["vc141"] set "VCVER=vc141" +set "BIN_DIR=win%ARCH%\%VCVER%\bind" +set "LIB_DIR=win%ARCH%\%VCVER%\libd" + +if ["%CASDEB%"] == [""] ( + set "BIN_DIR=win%ARCH%\%VCVER%\bin" + set "LIB_DIR=win%ARCH%\%VCVER%\lib" +) + +set "PATH=%~dp0%BIN_DIR%;%PATH%" + +if not "%QTDIR%" == "" ( + set "RES_DIR=%~dp0win%ARCH%\%VCVER%\res" + + set "CSF_ResourcesDefaults=!RES_DIR!" + set "CSF_TutorialResourcesDefaults=!RES_DIR!" + set "CSF_IEResourcesDefaults=!RES_DIR!" + + set "PATH=%QTDIR%/bin;%PATH%" + set "QT_QPA_PLATFORM_PLUGIN_PATH=%QTDIR%\plugins\platforms" +) diff --git a/samples/qt/OCCTOverview/env.sh b/samples/qt/OCCTOverview/env.sh new file mode 100644 index 0000000000..c161ee025b --- /dev/null +++ b/samples/qt/OCCTOverview/env.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +export aSamplePath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +if [ -e "custom.sh" ]; then + source "custom.sh" $*; +fi + +source ${CASROOT}/bin/env.sh $* + +if [ "${QTDIR}" != "" ]; then + export PATH=${QTDIR}/bin:${PATH} +else + aQMakePath=`which qmake` + echo "Environment variable \"QTDIR\" not defined.. Define it in \"custom.sh\" script." + if [ -x "$aQMakePath" ]; then + echo "qmake from PATH will be used instead." + else + exit 1 + fi +fi + +host=`uname -s` +export STATION=$host +export RES_DIR=${aSamplePath}/${STATION}/res diff --git a/samples/qt/OCCTOverview/genproj.bat b/samples/qt/OCCTOverview/genproj.bat new file mode 100644 index 0000000000..f3670f3eae --- /dev/null +++ b/samples/qt/OCCTOverview/genproj.bat @@ -0,0 +1,17 @@ +@echo off +REM Generation of vcproj files with qmake utilite +REM Variable QTDIR and PATH to qmake executable must be defined without fail + +REM Use first argument to specify version of Visual Studio (vc10, vc11, vc12 or vc14), +REM second argument specifies architecture) (win32 or win64) +REM third argument specifies Debug or Release mode + +call "%~dp0env.bat" %1 %2 %3 + +if ["%VCARCH%"] == [""] set "VCARCH=%ARCH%" +if ["%VCARCH%"] == ["64"] set "VCARCH=amd64" +if ["%VCARCH%"] == ["32"] set "VCARCH=x86" + +call "%VCVARS%" %VCARCH% + +qmake -tp vc -r -o OCCTOverview.sln OCCTOverview0.pro diff --git a/samples/qt/OCCTOverview/make.sh b/samples/qt/OCCTOverview/make.sh new file mode 100644 index 0000000000..421dc19817 --- /dev/null +++ b/samples/qt/OCCTOverview/make.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +export aSamplePath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +if [ -e "${aSamplePath}/env.sh" ]; then source "${aSamplePath}/env.sh" $*; fi + +cd $aSamplePath +qmake OCCTOverview.pro +if [ "$(uname -s)" != "Darwin" ] || [ "$MACOSX_USE_GLX" == "true" ]; then + aNbJobs="$(getconf _NPROCESSORS_ONLN)" + if [ "${CASDEB}" == "d" ]; then + make -j $aNbJobs debug + else + make -j $aNbJobs release + fi +fi diff --git a/samples/qt/OCCTOverview/msvc.bat b/samples/qt/OCCTOverview/msvc.bat new file mode 100644 index 0000000000..6164118ece --- /dev/null +++ b/samples/qt/OCCTOverview/msvc.bat @@ -0,0 +1,19 @@ +@echo off + +Setlocal EnableDelayedExpansion + +rem Setup environment +call "%~dp0env.bat" %1 %2 %3 + +rem Define path to project file +set "PRJFILE=%~dp0OCCTOverview.sln" + +rem Launch Visual Studio - either professional (devenv) or Express, as available +if exist "%DevEnvDir%\devenv.exe" ( + start "" "%DevEnvDir%\devenv.exe" "%PRJFILE%" +) else if exist "%DevEnvDir%\%VisualStudioExpressName%.exe" ( + start "" "%DevEnvDir%\%VisualStudioExpressName%.exe" "%PRJFILE%" +) else ( + echo Error: Could not find MS Visual Studio ^(%VCVER%^) + echo Check relevant environment variable ^(e.g. VS100COMNTOOLS for vc10^) +) diff --git a/samples/qt/OCCTOverview/res/antialiasing.png b/samples/qt/OCCTOverview/res/antialiasing.png new file mode 100644 index 0000000000..da8e5047a4 Binary files /dev/null and b/samples/qt/OCCTOverview/res/antialiasing.png differ diff --git a/samples/qt/OCCTOverview/res/cursor_rotate.png b/samples/qt/OCCTOverview/res/cursor_rotate.png new file mode 100644 index 0000000000..a3cb0c1ecc Binary files /dev/null and b/samples/qt/OCCTOverview/res/cursor_rotate.png differ diff --git a/samples/qt/OCCTOverview/res/cursor_zoom.png b/samples/qt/OCCTOverview/res/cursor_zoom.png new file mode 100644 index 0000000000..0020fea39f Binary files /dev/null and b/samples/qt/OCCTOverview/res/cursor_zoom.png differ diff --git a/samples/qt/OCCTOverview/res/help.png b/samples/qt/OCCTOverview/res/help.png new file mode 100644 index 0000000000..e57336285e Binary files /dev/null and b/samples/qt/OCCTOverview/res/help.png differ diff --git a/samples/qt/OCCTOverview/res/lamp.png b/samples/qt/OCCTOverview/res/lamp.png new file mode 100644 index 0000000000..a5a6775c33 Binary files /dev/null and b/samples/qt/OCCTOverview/res/lamp.png differ diff --git a/samples/qt/OCCTOverview/res/raytracing.png b/samples/qt/OCCTOverview/res/raytracing.png new file mode 100644 index 0000000000..211e697237 Binary files /dev/null and b/samples/qt/OCCTOverview/res/raytracing.png differ diff --git a/samples/qt/OCCTOverview/res/reflections.png b/samples/qt/OCCTOverview/res/reflections.png new file mode 100644 index 0000000000..ad48a95615 Binary files /dev/null and b/samples/qt/OCCTOverview/res/reflections.png differ diff --git a/samples/qt/OCCTOverview/res/shadows.png b/samples/qt/OCCTOverview/res/shadows.png new file mode 100644 index 0000000000..7562c12918 Binary files /dev/null and b/samples/qt/OCCTOverview/res/shadows.png differ diff --git a/samples/qt/OCCTOverview/res/tool_color.png b/samples/qt/OCCTOverview/res/tool_color.png new file mode 100644 index 0000000000..0daa160caf Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_color.png differ diff --git a/samples/qt/OCCTOverview/res/tool_delete.png b/samples/qt/OCCTOverview/res/tool_delete.png new file mode 100644 index 0000000000..3886af51d8 Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_delete.png differ diff --git a/samples/qt/OCCTOverview/res/tool_material.png b/samples/qt/OCCTOverview/res/tool_material.png new file mode 100644 index 0000000000..f846a56371 Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_material.png differ diff --git a/samples/qt/OCCTOverview/res/tool_shading.png b/samples/qt/OCCTOverview/res/tool_shading.png new file mode 100644 index 0000000000..6bb9dc46de Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_shading.png differ diff --git a/samples/qt/OCCTOverview/res/tool_transparency.png b/samples/qt/OCCTOverview/res/tool_transparency.png new file mode 100644 index 0000000000..786803a5cf Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_transparency.png differ diff --git a/samples/qt/OCCTOverview/res/tool_wireframe.png b/samples/qt/OCCTOverview/res/tool_wireframe.png new file mode 100644 index 0000000000..32ad5248ae Binary files /dev/null and b/samples/qt/OCCTOverview/res/tool_wireframe.png differ diff --git a/samples/qt/OCCTOverview/res/view_axo.png b/samples/qt/OCCTOverview/res/view_axo.png new file mode 100644 index 0000000000..4801ab4592 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_axo.png differ diff --git a/samples/qt/OCCTOverview/res/view_back.png b/samples/qt/OCCTOverview/res/view_back.png new file mode 100644 index 0000000000..0798f52938 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_back.png differ diff --git a/samples/qt/OCCTOverview/res/view_bottom.png b/samples/qt/OCCTOverview/res/view_bottom.png new file mode 100644 index 0000000000..c7cfdc208a Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_bottom.png differ diff --git a/samples/qt/OCCTOverview/res/view_comp_off.png b/samples/qt/OCCTOverview/res/view_comp_off.png new file mode 100644 index 0000000000..c900b196f0 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_comp_off.png differ diff --git a/samples/qt/OCCTOverview/res/view_comp_on.png b/samples/qt/OCCTOverview/res/view_comp_on.png new file mode 100644 index 0000000000..73ca4c83d0 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_comp_on.png differ diff --git a/samples/qt/OCCTOverview/res/view_fitall.png b/samples/qt/OCCTOverview/res/view_fitall.png new file mode 100644 index 0000000000..21d2f423ef Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_fitall.png differ diff --git a/samples/qt/OCCTOverview/res/view_front.png b/samples/qt/OCCTOverview/res/view_front.png new file mode 100644 index 0000000000..a9e99c59b6 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_front.png differ diff --git a/samples/qt/OCCTOverview/res/view_left.png b/samples/qt/OCCTOverview/res/view_left.png new file mode 100644 index 0000000000..7d25b6ab2f Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_left.png differ diff --git a/samples/qt/OCCTOverview/res/view_reset.png b/samples/qt/OCCTOverview/res/view_reset.png new file mode 100644 index 0000000000..38849fd694 Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_reset.png differ diff --git a/samples/qt/OCCTOverview/res/view_right.png b/samples/qt/OCCTOverview/res/view_right.png new file mode 100644 index 0000000000..5540220cfa Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_right.png differ diff --git a/samples/qt/OCCTOverview/res/view_top.png b/samples/qt/OCCTOverview/res/view_top.png new file mode 100644 index 0000000000..b788de36fb Binary files /dev/null and b/samples/qt/OCCTOverview/res/view_top.png differ diff --git a/samples/qt/OCCTOverview/run.bat b/samples/qt/OCCTOverview/run.bat new file mode 100644 index 0000000000..6c7bcbe24c --- /dev/null +++ b/samples/qt/OCCTOverview/run.bat @@ -0,0 +1,23 @@ +Setlocal EnableDelayedExpansion + +call "%~dp0env.bat" %1 %2 %3 %4 + +set "BIN_DIR=win%ARCH%\%VCVER%\bind" +if ["%CASDEB%"] == [""] ( + set "BIN_DIR=win%ARCH%\%VCVER%\bin" +) + +if not exist "%~dp0%BIN_DIR%\OCCTOverview.exe" goto ERR_EXE + +echo Starting OCCTOverview ..... +"%~dp0%BIN_DIR%\OCCTOverview.exe" %4 + +goto END + +:ERR_EXE +echo Executable %~dp0%BIN_DIR%\OCCTOverview.exe not found. +echo Probably you didn't compile the application. +pause +goto END + +:END \ No newline at end of file diff --git a/samples/qt/OCCTOverview/run.sh b/samples/qt/OCCTOverview/run.sh new file mode 100644 index 0000000000..7abe6f12a4 --- /dev/null +++ b/samples/qt/OCCTOverview/run.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +export aSamplePath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +if [ -e "${aSamplePath}/env.sh" ]; then source "${aSamplePath}/env.sh" $*; fi +cd $aSamplePath + +aSystem=`uname -s` +if [ "$aSystem" == "Darwin" ] && [ "$MACOSX_USE_GLX" != "true" ]; then + if [ "${CASDEB}" == "d" ]; then + BIN_DIR="${aSamplePath}/build/Debug/OCCTOverview.app/Contents/MacOS" + else + BIN_DIR="${aSamplePath}/build/Release/OCCTOverview.app/Contents/MacOS" + fi +else + BIN_DIR="${aSamplePath}/${STATION}/bin${CASDEB}" +fi + +CSF_ResourcesDefaults="${RES_DIR}" +CSF_TutorialResourcesDefaults="${RES_DIR}" + +PATH="${BIN_DIR}:${PATH}" + +export CSF_TutorialResourcesDefaults CSF_ResourcesDefaults +export PATH + +if test ! -r "${BIN_DIR}/OCCTOverview"; then + echo "Executable \"${BIN_DIR}/OCCTOverview\" not found." + if [ "$aSystem" == "Darwin" ] && [ "$MACOSX_USE_GLX" != "true" ]; then + echo "Probably you don't compile the application. Build it with Xcode." + else + echo "Probably you don't compile the application. Execute \"make\"." + fi + exit 1 +fi + +${BIN_DIR}/OCCTOverview diff --git a/samples/qt/OCCTOverview/src/ApplicationCommon.cxx b/samples/qt/OCCTOverview/src/ApplicationCommon.cxx new file mode 100644 index 0000000000..136a8e9133 --- /dev/null +++ b/samples/qt/OCCTOverview/src/ApplicationCommon.cxx @@ -0,0 +1,685 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "ApplicationCommon.h" + +#include <Standard_WarningsDisable.hxx> +#include <QApplication> +#include <QDir> +#include <QFile> +#include <QFont> +#include <QFrame> +#include <QGroupBox> +#include <QJsonArray> +#include <QJsonDocument> +#include <QJsonObject> +#include <QMap> +#include <QMdiArea> +#include <QMdiSubWindow> +#include <QMenuBar> +#include <QMessageBox> +#include <QPair> +#include <QSplitter> +#include <QStatusBar> +#include <QtGlobal> +#include <QHBoxLayout> +#include <QVBoxLayout> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +#include <OpenGl_GraphicDriver.hxx> +#include <OSD_Environment.hxx> + +#include <stdlib.h> +#include <memory> + +ApplicationCommonWindow::ApplicationCommonWindow (ApplicationType theCategory) +: QMainWindow (nullptr), + myStdToolBar (nullptr), + myViewBar (nullptr), + myCasCadeBar (nullptr), + myFilePopup (nullptr), + myCategoryPopup (nullptr) +{ + myAppType = theCategory; + mySampleMapper = new QSignalMapper(this); + myExchangeMapper = new QSignalMapper(this); + myOcafMapper = new QSignalMapper(this); + myViewer3dMapper = new QSignalMapper(this); + myViewer2dMapper = new QSignalMapper(this); + + myCategoryMapper = new QSignalMapper(this); + + connect(mySampleMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onProcessSample); + connect(myExchangeMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onProcessExchange); + connect(myOcafMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onProcessOcaf); + connect(myViewer3dMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onProcessViewer3d); + connect(myViewer2dMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onProcessViewer2d); + + connect(myCategoryMapper, static_cast<void (QSignalMapper::*)(const QString &)>(&QSignalMapper::mapped), + this, &ApplicationCommonWindow::onChangeCategory); + + setFocusPolicy(Qt::StrongFocus); + + QFont aCodeViewFont; + aCodeViewFont.setFamily("Courier"); + aCodeViewFont.setFixedPitch(true); + aCodeViewFont.setPointSize(10); + + QGroupBox* aCodeFrame = new QGroupBox(tr("Sample code")); + QVBoxLayout* aCodeLayout = new QVBoxLayout(aCodeFrame); + aCodeLayout->setContentsMargins(3, 3, 3, 3); + myCodeView = new QTextEdit(aCodeFrame); + aCodeLayout->addWidget(myCodeView); + myCodeView->setDocumentTitle("Code"); + myCodeView->setLineWrapMode(QTextEdit::NoWrap); + myCodeView->setReadOnly(true); + myCodeView->setFont(aCodeViewFont); + myCodeViewHighlighter = new OcctHighlighter(myCodeView->document()); + + QGroupBox* aResultFrame = new QGroupBox(tr("Output")); + QVBoxLayout* aResultLayout = new QVBoxLayout(aResultFrame); + aResultLayout->setContentsMargins(3, 3, 3, 3); + myResultView = new QTextEdit(aResultFrame); + aResultLayout->addWidget(myResultView); + myResultView->setDocumentTitle("Output"); + myResultView->setReadOnly(true); + myResultView->setFont(aCodeViewFont); + + QSplitter* aCodeResultSplitter = new QSplitter(Qt::Vertical); + aCodeResultSplitter->addWidget(aCodeFrame); + aCodeResultSplitter->addWidget(aResultFrame); + + myDocument3d = createNewDocument(); + myDocument2d = createNewDocument(); + + QFrame* aViewFrame = new QFrame; + aViewFrame->setFrameStyle(QFrame::Panel | QFrame::Sunken); + aViewFrame->setLineWidth(3); + QVBoxLayout* aViewLayout = new QVBoxLayout(aViewFrame); + aViewLayout->setContentsMargins(0, 0, 0, 0); + myGeomWidget = new GeomWidget(myDocument3d, myDocument2d, this); + aViewLayout->addWidget(myGeomWidget); + //myGeomWidget->setContentsMargins(0, 0, 0, 0); + QSplitter* aGeomTextSplitter = new QSplitter(Qt::Horizontal); + + aGeomTextSplitter->addWidget(aViewFrame); + aGeomTextSplitter->addWidget(aCodeResultSplitter); + aGeomTextSplitter->setStretchFactor(0, 1); + aGeomTextSplitter->setStretchFactor(1, 1); + QList<int> aSizeList{ 640, 640 }; + aGeomTextSplitter->setSizes(aSizeList); + setCentralWidget(aGeomTextSplitter); + + Q_INIT_RESOURCE(Samples); + + TCollection_AsciiString aSampleSourcePach = getSampleSourceDir(); + myGeometrySamples = new GeometrySamples(aSampleSourcePach, + myDocument3d->getContext()); + myTopologySamples = new TopologySamples(aSampleSourcePach, + myDocument3d->getContext()); + myTriangulationSamples = new TriangulationSamples(aSampleSourcePach, + myDocument3d->getContext()); + myDataExchangeSamples = new DataExchangeSamples(aSampleSourcePach, + myGeomWidget->Get3dView(), + myDocument3d->getContext()); + myOcafSamples = new OcafSamples(aSampleSourcePach, + myDocument3d->getViewer(), + myDocument3d->getContext()); + myViewer3dSamples = new Viewer3dSamples(aSampleSourcePach, + myGeomWidget->Get3dView(), + myDocument3d->getContext()); + myViewer2dSamples = new Viewer2dSamples(aSampleSourcePach, + myGeomWidget->Get2dView(), + myDocument2d->getViewer(), + myDocument2d->getContext()); + + MenuFormJson(":/menus/Geometry.json", mySampleMapper, myGeometryMenus); + MenuFormJson(":/menus/Topology.json", mySampleMapper, myTopologyMenus); + MenuFormJson(":/menus/Triangulation.json", mySampleMapper, myTriangulationMenus); + MenuFormJson(":/menus/DataExchange.json", myExchangeMapper, myDataExchangeMenus); + MenuFormJson(":/menus/Ocaf.json", myOcafMapper, myOcafMenus); + MenuFormJson(":/menus/Viewer3d.json", myViewer3dMapper, myViewer3dMenus); + MenuFormJson(":/menus/Viewer2d.json", myViewer2dMapper, myViewer2dMenus); + + onChangeCategory(ALL_CATEGORIES[myAppType]); + + resize(1280, 560); +} + +void ApplicationCommonWindow::RebuildMenu() +{ + menuBar()->clear(); + + myStdActions[FileQuit] = CreateAction(&ApplicationCommonWindow::onCloseAllWindows, "Quit", "CTRL+Q"); + myStdActions[HelpAbout] = CreateAction(&ApplicationCommonWindow::onAbout, "About", "F1", ":/icons/help.png"); + + // populate a menu with all actions + myFilePopup = new QMenu(this); + myFilePopup = menuBar()->addMenu(tr("&File")); + myFilePopup->addAction(myStdActions[FileQuit]); + + myCategoryPopup = new QMenu(this); + myCategoryPopup = menuBar()->addMenu(tr("&Category")); + + for (ApplicationType aCategory: ALL_CATEGORIES.keys()) + { + QString aCategoryName = ALL_CATEGORIES.value(aCategory); + QAction* anAction = myCategoryPopup->addAction(aCategoryName); + anAction->setText(aCategoryName); + myCategoryMapper->setMapping(anAction, aCategoryName); + connect(anAction, &QAction::triggered, myCategoryMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map)); + myCategoryPopup->addAction(anAction); + myCategoryActions.insert(aCategory, anAction); + } + + for (QMenu* aSampleMenu : GetCurrentMenus()) + { + menuBar()->addMenu(aSampleMenu); + } + + // add a help menu + QMenu* aHelp = new QMenu(this); + menuBar()->addSeparator(); + aHelp = menuBar()->addMenu(tr("&Help")); + aHelp->addAction(myStdActions[HelpAbout]); +} + +Handle(BaseSample) ApplicationCommonWindow::GetCurrentSamples() +{ + switch (myAppType) + { + case Geometry: return myGeometrySamples; + case Topology: return myTopologySamples; + case Triangulation: return myTriangulationSamples; + case DataExchange: return myDataExchangeSamples; + case Ocaf: return myOcafSamples; + case Viewer2d: return myViewer2dSamples; + case Viewer3d: return myViewer3dSamples; + case Unknown: + break; + } + throw QString("Unknown Application type"); +} + +const QList<QMenu*>& ApplicationCommonWindow::GetCurrentMenus() +{ + switch (myAppType) + { + case Geometry: return myGeometryMenus; + case Topology: return myTopologyMenus; + case Triangulation: return myTriangulationMenus; + case DataExchange: return myDataExchangeMenus; + case Ocaf: return myOcafMenus; + case Viewer2d: return myViewer2dMenus; + case Viewer3d: return myViewer3dMenus; + case Unknown: + break; + } + throw QString("Unknown Application type"); +} + +DocumentCommon* ApplicationCommonWindow::createNewDocument() +{ + return new DocumentCommon(this); +} + +void ApplicationCommonWindow::onChangeCategory(const QString& theCategory) +{ + myAppType = ALL_CATEGORIES.key(theCategory); + setWindowTitle(ALL_CATEGORIES[myAppType]); + + myOcafSamples->ClearExtra(); + myViewer3dSamples->ClearExtra(); + myViewer2dSamples->ClearExtra(); + + GetCurrentSamples()->Clear(); + myDocument3d->Clear(); + myDocument2d->Clear(); + + myCodeView->setPlainText(""); + myResultView->setPlainText(""); + GetCurrentSamples()->AppendCube(); + myDocument3d->SetObjects(GetCurrentSamples()->Get3dObjects()); + myGeomWidget->FitAll(); + + RebuildMenu(); + + switch (myAppType) + { + case DataExchange: + { + myDataExchangeSamples->AppendBottle(); + myDocument3d->SetObjects(GetCurrentSamples()->Get3dObjects()); + myGeomWidget->Show3d(); + break; + } + case Ocaf: + { + onProcessOcaf("CreateOcafDocument"); + myGeomWidget->Show3d(); + break; + } + case Viewer2d: + { + myGeomWidget->Show2d(); + break; + } + case Viewer3d: + { + myViewer3dSamples->AppendBottle(); + myDocument3d->SetObjects(GetCurrentSamples()->Get3dObjects()); + myGeomWidget->Show3d(); + break; + } + case Geometry: + case Topology: + case Triangulation: + case Unknown: + { + break; + } + } +} + +void ApplicationCommonWindow::onAbout() +{ + QMessageBox::information(this, tr("OCCT Overview"), + tr("Qt based application to study OpenCASCADE Technology"), + tr("Ok"), QString::null, QString::null, 0, 0); +} + +TCollection_AsciiString ApplicationCommonWindow::getSampleSourceDir() +{ + TCollection_AsciiString aSampleSourceDir = OSD_Environment("CSF_OCCTOverviewSampleCodePath").Value(); + if (aSampleSourceDir.IsEmpty()) + { + TCollection_AsciiString aCasRoot = OSD_Environment("CASROOT").Value(); + if (!aCasRoot.IsEmpty()) + { + aSampleSourceDir = aCasRoot + "/samples/OCCTOverview/code"; + } + } + return aSampleSourceDir; +} + +template <typename PointerToMemberFunction> +QAction* ApplicationCommonWindow::CreateAction (PointerToMemberFunction theHandlerMethod, + const QString& theActionName, + const QString& theShortcut, + const QString& theIconName) +{ + QAction* aAction(NULL); + if (theIconName.isEmpty()) + { + aAction = new QAction(theActionName, this); + } + else + { + QPixmap aIcon = QPixmap(theIconName); + aAction = new QAction(aIcon, theActionName, this); + } + aAction->setToolTip(theActionName); + aAction->setStatusTip(theActionName); + aAction->setShortcut(theShortcut); + connect(aAction, &QAction::triggered, this, theHandlerMethod); + return aAction; +} + +template <typename PointerToMemberFunction> +QAction* ApplicationCommonWindow::CreateSample (PointerToMemberFunction theHandlerMethod, + const char* theActionName) +{ + QAction* aAction = new QAction(QObject::tr(theActionName), this); + connect(aAction, &QAction::triggered, this, theHandlerMethod); + return aAction; +} + +void ApplicationCommonWindow::resizeEvent(QResizeEvent* e) +{ + QMainWindow::resizeEvent(e); + statusBar()->setSizeGripEnabled(!isMaximized()); +} + +void ApplicationCommonWindow::onProcessSample(const QString& theSampleName) +{ + QApplication::setOverrideCursor(Qt::WaitCursor); + setWindowTitle(ALL_CATEGORIES[myAppType] + " - " + theSampleName); + GetCurrentSamples()->Process(theSampleName.toUtf8().data()); + myDocument3d->SetObjects(GetCurrentSamples()->Get3dObjects()); + myDocument2d->SetObjects(GetCurrentSamples()->Get2dObjects()); + myCodeView->setPlainText(GetCurrentSamples()->GetCode().ToCString()); + myResultView->setPlainText(GetCurrentSamples()->GetResult().ToCString()); + myGeomWidget->FitAll(); + QApplication::restoreOverrideCursor(); +} + +void ApplicationCommonWindow::onProcessExchange(const QString& theSampleName) +{ + setWindowTitle(ALL_CATEGORIES[myAppType] + " - " + theSampleName); + int aMode = 0; + QString aFileName = selectFileName(theSampleName, getDataExchangeDialog(theSampleName), aMode); + if (aFileName.isEmpty()) + { + return; + } + + QApplication::setOverrideCursor(Qt::WaitCursor); + myDataExchangeSamples->SetFileName(aFileName.toUtf8().data()); + myDataExchangeSamples->SetStepType(static_cast<STEPControl_StepModelType>(aMode)); + myDataExchangeSamples->Process(theSampleName.toUtf8().data()); + myDocument3d->SetObjects(myDataExchangeSamples->Get3dObjects()); + myDocument2d->SetObjects(myDataExchangeSamples->Get2dObjects()); + myCodeView->setPlainText(myDataExchangeSamples->GetCode().ToCString()); + myResultView->setPlainText(myDataExchangeSamples->GetResult().ToCString()); + myGeomWidget->FitAll(); + QApplication::restoreOverrideCursor(); +} + +void ApplicationCommonWindow::onProcessOcaf(const QString& theSampleName) +{ + setWindowTitle(ALL_CATEGORIES[myAppType] + " - " + theSampleName); + + if (theSampleName.indexOf("Dialog") == 0) + { + int aMode = 0; // not used + QString aFileName = selectFileName(theSampleName, getOcafDialog(theSampleName), aMode); + if (aFileName.isEmpty()) + { + return; + } + myOcafSamples->SetFileName(aFileName.toUtf8().data()); + } + QApplication::setOverrideCursor(Qt::WaitCursor); + myOcafSamples->Process(theSampleName.toUtf8().data()); + myDocument2d->SetObjects(myOcafSamples->Get2dObjects()); + myCodeView->setPlainText(myOcafSamples->GetCode().ToCString()); + myResultView->setPlainText(myOcafSamples->GetResult().ToCString()); + QApplication::restoreOverrideCursor(); +} + +void ApplicationCommonWindow::onProcessViewer3d(const QString& theSampleName) +{ + setWindowTitle(ALL_CATEGORIES[myAppType] + " - " + theSampleName); + + QApplication::setOverrideCursor(Qt::WaitCursor); + myViewer3dSamples->Process(theSampleName.toUtf8().data()); + myCodeView->setPlainText(myViewer3dSamples->GetCode().ToCString()); + myResultView->setPlainText(myViewer3dSamples->GetResult().ToCString()); + myGeomWidget->FitAll(); + QApplication::restoreOverrideCursor(); +} + +void ApplicationCommonWindow::onProcessViewer2d(const QString& theSampleName) +{ + setWindowTitle(ALL_CATEGORIES[myAppType] + " - " + theSampleName); + + Standard_Boolean anIsFileSample = Viewer2dSamples::IsFileSample(theSampleName.toUtf8().data()); + QString aFileName; + if (anIsFileSample) + { + int aMode = 0; // not used + aFileName = selectFileName(theSampleName, getOcafDialog(theSampleName), aMode); + if (aFileName.isEmpty()) + { + return; + } + + myViewer2dSamples->SetFileName(aFileName.toUtf8().data()); + } + if (!anIsFileSample || (anIsFileSample && !aFileName.isEmpty())) + { + QApplication::setOverrideCursor(Qt::WaitCursor); + myViewer2dSamples->Process(theSampleName.toUtf8().data()); + if (!Viewer2dSamples::IsShadedSample(theSampleName.toUtf8().data())) + { + myDocument2d->SetObjects(myViewer2dSamples->Get2dObjects(), Standard_False); + } + else + { + myDocument2d->SetObjects(myViewer2dSamples->Get2dObjects(), Standard_True); + } + myCodeView->setPlainText(myViewer2dSamples->GetCode().ToCString()); + myResultView->setPlainText(myViewer2dSamples->GetResult().ToCString()); + myGeomWidget->Show2d(); + QApplication::restoreOverrideCursor(); + } + else + { + myResultView->setPlainText("No file selected!"); + } +} + +QString ApplicationCommonWindow::selectFileName(const QString& theSampleName, + TranslateDialog* theDialog, int& theMode) +{ + Q_UNUSED(theSampleName) + + std::shared_ptr<TranslateDialog> aDialog(theDialog); + + int ret = aDialog->exec(); + theMode = aDialog->getMode(); + + qApp->processEvents(); + + QString aFilename; + QStringList aFileNameList; + if (ret != QDialog::Accepted) + { + return aFilename; + } + aFileNameList = aDialog->selectedFiles(); + if (!aFileNameList.isEmpty()) + { + aFilename = aFileNameList[0]; + } + + if (!QFileInfo(aFilename).completeSuffix().length()) + { + QString selFilter = aDialog->selectedNameFilter(); + int idx = selFilter.indexOf("(*."); + if (idx != -1) + { + QString tail = selFilter.mid(idx + 3); + idx = tail.indexOf(" "); + if (idx == -1) + { + idx = tail.indexOf(")"); + } + QString ext = tail.left(idx); + if (ext.length()) + { + aFilename += QString(".") + ext; + } + } + } + + return aFilename; +} + +TranslateDialog* ApplicationCommonWindow::getDataExchangeDialog(const QString& theSampleName) +{ + TranslateDialog* aTranslateDialog = new TranslateDialog(this, 0, true); + TCollection_AsciiString aSampleName(theSampleName.toUtf8().data()); + + if (DataExchangeSamples::IsExportSample(aSampleName)) + { + aTranslateDialog->setWindowTitle("Export file"); + aTranslateDialog->setFileMode(QFileDialog::AnyFile); + aTranslateDialog->setAcceptMode(QFileDialog::AcceptSave); + } + else if (DataExchangeSamples::IsImportSample(aSampleName)) + { + aTranslateDialog->setWindowTitle("Import file"); + aTranslateDialog->setFileMode(QFileDialog::ExistingFile); + aTranslateDialog->setAcceptMode(QFileDialog::AcceptOpen); + } + QString aFormatFilter; + if (DataExchangeSamples::IsBrepSample(aSampleName)) + { + aFormatFilter = "BREP Files(*.brep *.rle)"; + } + else if (DataExchangeSamples::IsStepSample(aSampleName)) + { + aFormatFilter = "STEP Files (*.stp *.step)"; + aTranslateDialog->addMode(STEPControl_ManifoldSolidBrep, "Manifold Solid Brep"); + aTranslateDialog->addMode(STEPControl_FacetedBrep, "Faceted Brep"); + aTranslateDialog->addMode(STEPControl_ShellBasedSurfaceModel, "Shell Based Surface Model"); + aTranslateDialog->addMode(STEPControl_GeometricCurveSet, "Geometric Curve Set"); + } + else if (DataExchangeSamples::IsIgesSample(aSampleName)) + { + aFormatFilter = "IGES Files (*.igs *.iges)"; + } + else if (DataExchangeSamples::IsStlSample(aSampleName)) + { + aFormatFilter = "STL Files (*.stl)"; + } + else if (DataExchangeSamples::IsVrmlSample(aSampleName)) + { + aFormatFilter = "VRML Files (*.vrml)"; + } + else if (DataExchangeSamples::IsImageSample(aSampleName)) + { + aFormatFilter = "All Image Files (*.bmp *.gif *.jpg *.jpeg *.png *.tga)"; + } + QStringList aFilters; + aFilters.append(aFormatFilter); + aFilters.append("All Files(*.*)"); + + aTranslateDialog->setNameFilters(aFilters); + aTranslateDialog->clear(); + return aTranslateDialog; +} + +TranslateDialog* ApplicationCommonWindow::getOcafDialog(const QString& theSampleName) +{ + TranslateDialog* aTranslateDialog = new TranslateDialog(this, 0, true); + TCollection_AsciiString aSampleName(theSampleName.toUtf8().data()); + + if (OcafSamples::IsExportSample(aSampleName)) + { + aTranslateDialog->setWindowTitle("Export file"); + aTranslateDialog->setFileMode(QFileDialog::AnyFile); + aTranslateDialog->setAcceptMode(QFileDialog::AcceptSave); + } + else if (OcafSamples::IsImportSample(aSampleName)) + { + aTranslateDialog->setWindowTitle("Import file"); + aTranslateDialog->setFileMode(QFileDialog::ExistingFile); + aTranslateDialog->setAcceptMode(QFileDialog::AcceptOpen); + } + QStringList aFilters; + if (OcafSamples::IsBinarySample(aSampleName)) + { + aFilters.append("Binary OCAF Sample (*.cbf)"); + } + if (OcafSamples::IsXmlSample(aSampleName)) + { + aFilters.append("XML OCAF Sample (*.xml)"); + } + aFilters.append("All Files(*.*)"); + + aTranslateDialog->setNameFilters(aFilters); + aTranslateDialog->clear(); + return aTranslateDialog; +} + +QMenu* ApplicationCommonWindow::MenuFromJsonObject (const QJsonValue& theJsonValue, + const QString& theKey, + QWidget* theParent, + QSignalMapper* theMapper) +{ + QMenu* aMenu = new QMenu(theKey, theParent); + if (theJsonValue.isObject()) + { + QJsonObject aBranchObject = theJsonValue.toObject(); + for (const QString& aBranchKey : aBranchObject.keys()) + { + aMenu->addMenu(MenuFromJsonObject(aBranchObject.value(aBranchKey), aBranchKey, aMenu, theMapper)); + } + } + else if (theJsonValue.isArray()) + { + QJsonArray aDataArray = theJsonValue.toArray(); + for (const QJsonValue& aDataValue : aDataArray) + { + if (aDataValue.isObject()) + { + QJsonObject aDataObject = aDataValue.toObject(); + QString aSampleName = aDataObject["function"].toString(); + QAction* anAction = aMenu->addAction(aSampleName); + anAction->setText(aDataObject["text"].toString()); + + theMapper->setMapping(anAction, aSampleName); + connect(anAction, &QAction::triggered, theMapper, + static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map)); + } + } + } + return aMenu; +} + +void ApplicationCommonWindow::MenuFormJson (const QString& thePath, + QSignalMapper* theMapper, + QList<QMenu*>& theMunusList) +{ + theMunusList.clear(); + QFile aJsonFile(thePath); + QString anErrorMessage; + if (aJsonFile.error() != QFile::NoError) + { + anErrorMessage = aJsonFile.errorString(); + Message::SendFail() << "QFile creating error: " << anErrorMessage.toUtf8().constData(); + return; + } + if (!aJsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) + { + Message::SendFail() << "File " << thePath.toUtf8().constData() << " could not open"; + if (aJsonFile.error() != QFile::NoError) + { + anErrorMessage = aJsonFile.errorString(); + Message::SendFail() << "QFile opening error: " << anErrorMessage.toUtf8().constData(); + } + return; + } + QString aJsonString = aJsonFile.readAll(); + aJsonFile.close(); + + QJsonDocument aJsonDoc = QJsonDocument::fromJson(aJsonString.toUtf8()); + if (aJsonDoc.isObject()) + { + QJsonObject aJsonObj = aJsonDoc.object(); + for (const QString& aKey : aJsonObj.keys()) + { + QJsonValue aJsonValue = aJsonObj.value(aKey); + if (aJsonValue.isObject()) + { + theMunusList.push_back(MenuFromJsonObject(aJsonValue.toObject(), aKey, this, theMapper)); + } + } + } +} diff --git a/samples/qt/OCCTOverview/src/ApplicationCommon.h b/samples/qt/OCCTOverview/src/ApplicationCommon.h new file mode 100644 index 0000000000..4adcab05cc --- /dev/null +++ b/samples/qt/OCCTOverview/src/ApplicationCommon.h @@ -0,0 +1,197 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef APPLICATION_COMMON_OVERVIEW_H +#define APPLICATION_COMMON_OVERVIEW_H + +#include "BaseSample.h" +#include "CommonSample.h" +#include "DataExchangeSamples.h" +#include "DocumentCommon.h" +#include "GeometrySamples.h" +#include "GeomWidget.h" +#include "OcafSamples.h" +#include "OcctHighlighter.h" +#include "TopologySamples.h" +#include "TranslateDialog.h" +#include "TriangulationSamples.h" +#include "View.h" +#include "Viewer2dSamples.h" +#include "Viewer3dSamples.h" + +#include <Standard_WarningsDisable.hxx> +#include <QApplication> +#include <QAction> +#include <QList> +#include <QMainWindow> +#include <QMdiArea> +#include <QMenu> +#include <QSignalMapper> +#include <QToolBar> +#include <QTextEdit> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +enum StdActions +{ + FileNew, FilePrefUseVBO, FileClose, FilePreferences, FileQuit, ViewTool, ViewStatus, HelpAbout +}; + +enum ToolActions +{ + ToolWireframe, ToolShading, ToolColor, ToolMaterial, ToolTransparency, ToolDelete +}; + +enum ApplicationType +{ + Geometry, + Topology, + Triangulation, + DataExchange, + Ocaf, + Viewer2d, + Viewer3d, + Unknown +}; + +const QMap<ApplicationType, QString> ALL_CATEGORIES = +{ + { ApplicationType::Geometry,"Geometry"}, + { ApplicationType::Topology, "Topology"}, + { ApplicationType::Triangulation, "Triangulation"}, + { ApplicationType::DataExchange, "DataExchange"}, + { ApplicationType::Ocaf, "OCAF"}, + { ApplicationType::Viewer3d, "3D viewer"}, + { ApplicationType::Viewer2d, "2D Viewer"} +}; + +//! Main application window +class COMMONSAMPLE_EXPORT ApplicationCommonWindow: public QMainWindow +{ + Q_OBJECT + +public: + ApplicationCommonWindow(ApplicationType theCategory); + + ApplicationType GetApplicationType() const { return myAppType; } + void SetApplicationType(ApplicationType theApplicationType) { myAppType = theApplicationType; } + + static TCollection_AsciiString getSampleSourceDir(); + +protected: + virtual DocumentCommon* createNewDocument(); + +public slots: + virtual void onAbout(); + virtual void onChangeCategory(const QString& theCategory); + +protected: + template <typename PointerToMemberFunction> + QAction* CreateAction(PointerToMemberFunction theHandlerMethod, + const QString& theActionName, + const QString& theShortcut = "", + const QString& theIconName = ""); + + template <typename PointerToMemberFunction> + QAction* CreateSample(PointerToMemberFunction theHandlerMethod, + const char* theActionName); + + virtual void resizeEvent( QResizeEvent* ); + QMenu* getFilePopup() { return myFilePopup; } + QToolBar* getCasCadeBar() { return myCasCadeBar; } + + QMenu* MenuFromJsonObject (const QJsonValue& theJsonValue, + const QString& theKey, + QWidget* theParent, + QSignalMapper* theMapper); + void MenuFormJson (const QString& thePath, + QSignalMapper* theMapper, + QList<QMenu*>& theMunusList); + +private slots: + void onCloseAllWindows() { qApp->closeAllWindows(); } + + void onProcessSample(const QString& theSampleName); + void onProcessExchange(const QString& theSampleName); + void onProcessOcaf(const QString& theSampleName); + void onProcessViewer3d(const QString& theSampleName); + void onProcessViewer2d(const QString& theSampleName); + +private: + + void RebuildMenu(); + Handle(BaseSample) GetCurrentSamples(); + const QList<QMenu*>& GetCurrentMenus(); + + QString selectFileName(const QString& theSampleName, TranslateDialog* theDialog, int& theMode); + TranslateDialog* getDataExchangeDialog(const QString& theSampleName); + TranslateDialog* getOcafDialog(const QString& theSampleName); + +private: + ApplicationType myAppType; + + Handle(GeometrySamples) myGeometrySamples; + Handle(TopologySamples) myTopologySamples; + Handle(TriangulationSamples) myTriangulationSamples; + Handle(DataExchangeSamples) myDataExchangeSamples; + Handle(OcafSamples) myOcafSamples; + Handle(Viewer3dSamples) myViewer3dSamples; + Handle(Viewer2dSamples) myViewer2dSamples; + + QMap<StdActions, QAction*> myStdActions; + QMap<ApplicationType, QAction*> myCategoryActions; + QMap<ToolActions, QAction*> myToolActions; + QMap<Graphic3d_NameOfMaterial, QAction*> myMaterialActions; + + QToolBar* myStdToolBar; + QToolBar* myViewBar; + QToolBar* myCasCadeBar; + QMenu* myFilePopup; + QMenu* myCategoryPopup; + +// QList<QMenu*> mySamplePopups; + QList<QMenu*> myGeometryMenus; + QList<QMenu*> myTopologyMenus; + QList<QMenu*> myTriangulationMenus; + QList<QMenu*> myDataExchangeMenus; + QList<QMenu*> myOcafMenus; + QList<QMenu*> myViewer3dMenus; + QList<QMenu*> myViewer2dMenus; + + QSignalMapper* mySampleMapper; + QSignalMapper* myExchangeMapper; + QSignalMapper* myOcafMapper; + QSignalMapper* myViewer3dMapper; + QSignalMapper* myViewer2dMapper; + + QSignalMapper* myCategoryMapper; + + QTextEdit* myCodeView; + QTextEdit* myResultView; + OcctHighlighter* myCodeViewHighlighter; + + GeomWidget* myGeomWidget; + + DocumentCommon* myDocument3d; + DocumentCommon* myDocument2d; +}; + +#endif diff --git a/samples/qt/OCCTOverview/src/CommonSample.h b/samples/qt/OCCTOverview/src/CommonSample.h new file mode 100644 index 0000000000..0bb38acba6 --- /dev/null +++ b/samples/qt/OCCTOverview/src/CommonSample.h @@ -0,0 +1,43 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef COMMONSAMPLE_H +#define COMMONSAMPLE_H + +#ifndef NO_COMMONSAMPLE_EXPORTS +#ifdef COMMONSAMPLE_EXPORTS +#ifdef _WIN32 +#define COMMONSAMPLE_EXPORT __declspec( dllexport ) +#else +#define COMMONSAMPLE_EXPORT +#endif +#else +#ifdef _WIN32 +#define COMMONSAMPLE_EXPORT __declspec( dllimport ) +#else +#define COMMONSAMPLE_EXPORT +#endif +#endif +#else +#define COMMONSAMPLE_EXPORT +#endif + +#endif diff --git a/samples/qt/OCCTOverview/src/DocumentCommon.cxx b/samples/qt/OCCTOverview/src/DocumentCommon.cxx new file mode 100644 index 0000000000..1eb018aba5 --- /dev/null +++ b/samples/qt/OCCTOverview/src/DocumentCommon.cxx @@ -0,0 +1,108 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "DocumentCommon.h" + +#include "ApplicationCommon.h" +#include "Transparency.h" + +#include <Standard_WarningsDisable.hxx> +#include <QApplication> +#include <QColor> +#include <QColorDialog> +#include <QStatusBar> +#include <Standard_WarningsRestore.hxx> + +#include <AIS_InteractiveObject.hxx> +#include <Aspect_DisplayConnection.hxx> +#include <Graphic3d_NameOfMaterial.hxx> +#include <OpenGl_GraphicDriver.hxx> +#include <OSD_Environment.hxx> + +#include <TCollection_AsciiString.hxx> + +// ======================================================================= +// function : Viewer +// purpose : +// ======================================================================= +Handle(V3d_Viewer) DocumentCommon::Viewer(const Standard_ExtString, + const Standard_CString, + const Standard_Real theViewSize, + const V3d_TypeOfOrientation theViewProj, + const Standard_Boolean theComputedMode, + const Standard_Boolean theDefaultComputedMode) +{ + static Handle(OpenGl_GraphicDriver) aGraphicDriver; + if (aGraphicDriver.IsNull()) + { + Handle(Aspect_DisplayConnection) aDisplayConnection; +#if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) + aDisplayConnection = new Aspect_DisplayConnection(OSD_Environment("DISPLAY").Value()); +#endif + aGraphicDriver = new OpenGl_GraphicDriver(aDisplayConnection); + } + + Handle(V3d_Viewer) aViewer = new V3d_Viewer(aGraphicDriver); + aViewer->SetDefaultViewSize(theViewSize); + aViewer->SetDefaultViewProj(theViewProj); + aViewer->SetComputedMode(theComputedMode); + aViewer->SetDefaultComputedMode(theDefaultComputedMode); + return aViewer; +} + +DocumentCommon::DocumentCommon(ApplicationCommonWindow* theApp) +: QObject (theApp), + myContextIsEmpty(true) +{ + TCollection_ExtendedString a3DName("Visu3D"); + + myViewer = Viewer(a3DName.ToExtString(), "", 1000.0, V3d_XposYnegZpos, Standard_True, Standard_True); + + myViewer->SetDefaultLights(); + myViewer->SetLightOn(); + + myContext = new AIS_InteractiveContext(myViewer); +} + +void DocumentCommon::SetObjects (const NCollection_Vector<Handle(AIS_InteractiveObject)>& theObjects, + Standard_Boolean theDisplayShaded) +{ + myContext->RemoveAll(Standard_False); + myContextIsEmpty = theObjects.IsEmpty(); + for (const Handle(AIS_InteractiveObject) anObject : theObjects) + { + if (!theDisplayShaded) + { + myContext->Display(anObject, Standard_False); + } + else + { + myContext->Display(anObject, AIS_Shaded, 0, Standard_False); + } + } + myViewer->Redraw(); +} + +void DocumentCommon::Clear() +{ + myContext->RemoveAll(Standard_True); + myContextIsEmpty = true; +} diff --git a/samples/qt/OCCTOverview/src/DocumentCommon.h b/samples/qt/OCCTOverview/src/DocumentCommon.h new file mode 100644 index 0000000000..b9c0fd312f --- /dev/null +++ b/samples/qt/OCCTOverview/src/DocumentCommon.h @@ -0,0 +1,75 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef DOCUMENT_COMMON_OVERVIEW_H +#define DOCUMENT_COMMON_OVERVIEW_H + +#include "CommonSample.h" + +#include <Standard_WarningsDisable.hxx> +#include <QObject> +#include <QList> +#include <Standard_WarningsRestore.hxx> + +#include <AIS_InteractiveContext.hxx> +#include <V3d_Viewer.hxx> + +class ApplicationCommonWindow; + +//! Implements visualization of samples content +class COMMONSAMPLE_EXPORT DocumentCommon : public QObject +{ + Q_OBJECT +public: + + DocumentCommon(ApplicationCommonWindow* ); + ~DocumentCommon() { } + + const Handle(AIS_InteractiveContext)& getContext() { return myContext; } + + const Handle(V3d_Viewer)& getViewer() { return myViewer; } + + void setViewer (const Handle(V3d_Viewer)& theViewer) { myViewer = theViewer; } + + void SetObjects(const NCollection_Vector<Handle(AIS_InteractiveObject)>& theObjects, + Standard_Boolean theDisplayShaded = Standard_False); + void Clear(); + bool IsEmpty() const { return myContextIsEmpty; } + +signals: + void selectionChanged(); + void sendCloseDocument( DocumentCommon* ); + +private: + Handle(V3d_Viewer) Viewer (const Standard_ExtString theName, + const Standard_CString theDomain, + const Standard_Real theViewSize, + const V3d_TypeOfOrientation theViewProj, + const Standard_Boolean theComputedMode, + const Standard_Boolean theDefaultComputedMode ); + +private: + Handle(V3d_Viewer) myViewer; + Handle(AIS_InteractiveContext) myContext; + bool myContextIsEmpty; +}; + +#endif diff --git a/samples/qt/OCCTOverview/src/FILES b/samples/qt/OCCTOverview/src/FILES new file mode 100644 index 0000000000..64a1f81afc --- /dev/null +++ b/samples/qt/OCCTOverview/src/FILES @@ -0,0 +1,19 @@ +ApplicationCommon.cxx +ApplicationCommon.h +CommonSample.h +DocumentCommon.cxx +DocumentCommon.h +GeomWidget.cxx +GeomWidget.h +Main.cxx +OcctHighlighter.cxx +OcctHighlighter.h +OcctWindow.cxx +OcctWindow.h +OCCTOverview.qrc +TranslateDialog.h +TranslateDialog.cxx +Transparency.cxx +Transparency.h +View.cxx +View.h diff --git a/samples/qt/OCCTOverview/src/GeomWidget.cxx b/samples/qt/OCCTOverview/src/GeomWidget.cxx new file mode 100644 index 0000000000..a1c0438726 --- /dev/null +++ b/samples/qt/OCCTOverview/src/GeomWidget.cxx @@ -0,0 +1,100 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "GeomWidget.h" + +#include <Standard_WarningsDisable.hxx> +#include <QFrame> +#include <QBoxLayout> +#include <QTextEdit> +#include <QStackedLayout> +#include <QToolBar> +#include <QStackedWidget> +#include <Standard_WarningsRestore.hxx> + +GeomWidget::GeomWidget (DocumentCommon* theDocument3d, + DocumentCommon* theDocument2d, + QWidget* theParent) +: QWidget (theParent), + myDocument3d(theDocument3d), + myDocument2d(theDocument2d) +{ + QVBoxLayout* aMainLayout = new QVBoxLayout(this); + aMainLayout->setContentsMargins(0, 0, 0, 0); + + my2dVidget = new QWidget; + QVBoxLayout* a2dLayout = new QVBoxLayout(my2dVidget); + a2dLayout->setContentsMargins(0, 0, 0, 0); + a2dLayout->setSpacing(0); + myView2d = new View(myDocument2d->getContext(), false, this); + QToolBar* aToolBar2d = new QToolBar; + aToolBar2d->addActions(myView2d->getViewActions()); + a2dLayout->addWidget(aToolBar2d); + a2dLayout->addWidget(myView2d); + + my3dVidget = new QWidget; + QVBoxLayout* a3dLayout = new QVBoxLayout(my3dVidget); + a3dLayout->setContentsMargins(0, 0, 0, 0); + a3dLayout->setSpacing(0); + myView3d = new View(myDocument3d->getContext(), true, this); + QToolBar* aToolBar3d = new QToolBar; + aToolBar3d->addActions(myView3d->getViewActions()); + aToolBar3d->addSeparator(); + aToolBar3d->addActions(myView3d->getRaytraceActions()); + a3dLayout->addWidget(aToolBar3d); + a3dLayout->addWidget(myView3d); + + myStackWidget = new QStackedWidget(this); + aMainLayout->addWidget(myStackWidget); + myStackWidget->addWidget(my2dVidget); + myStackWidget->addWidget(my3dVidget); + + FitAll(); +} + +void GeomWidget::FitAll() +{ + if (myDocument2d->IsEmpty()) + Show3d(); + else + Show2d(); +} + +void GeomWidget::Show3d() +{ + myView3d->axo(); + myView3d->fitAll(); + QAction* aShadingAction = myView3d->getViewAction(ViewAction::Shading); + aShadingAction->trigger(); + aShadingAction->setChecked(true); + QAction* aHlrOffAction = myView3d->getViewAction(ViewAction::HlrOff); + aHlrOffAction->trigger(); + aHlrOffAction->setChecked(true); + myStackWidget->setCurrentWidget(my3dVidget); + setStatusTip("Mouse buttons: Right-Zoom, Middle-Pan, Left-Rotate"); +} + +void GeomWidget::Show2d() +{ + myView2d->fitAll(); + myStackWidget->setCurrentWidget(my2dVidget); + setStatusTip("Mouse buttons: Right-Zoom, Middle-Pan"); +} diff --git a/samples/qt/OCCTOverview/src/GeomWidget.h b/samples/qt/OCCTOverview/src/GeomWidget.h new file mode 100644 index 0000000000..77165c6c89 --- /dev/null +++ b/samples/qt/OCCTOverview/src/GeomWidget.h @@ -0,0 +1,65 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef GEOMWIDGET_H +#define GEOMWIDGET_H + +#include "View.h" +#include "DocumentCommon.h" + +#include <Standard_WarningsDisable.hxx> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +class ApplicationCommon; +class QStackedWidget; + +//! Qt widget for organize 3D & 2D documents +class GeomWidget : public QWidget +{ + Q_OBJECT +public: + GeomWidget(DocumentCommon* theDocument3d, + DocumentCommon* theDocument2d, + QWidget* theParent = nullptr); + + void FitAll(); + + Handle(V3d_View) Get3dView() { return myView3d->getView(); } + + Handle(V3d_View) Get2dView() { return myView2d->getView(); } + + void Show3d(); + void Show2d(); + +private: + View* myView3d; + View* myView2d; + + QWidget* my3dVidget; + QWidget* my2dVidget; + QStackedWidget* myStackWidget; + + DocumentCommon* myDocument3d; + DocumentCommon* myDocument2d; +}; + +#endif //GEOMWIDGET_H diff --git a/samples/qt/OCCTOverview/src/Main.cxx b/samples/qt/OCCTOverview/src/Main.cxx new file mode 100644 index 0000000000..675d5646b7 --- /dev/null +++ b/samples/qt/OCCTOverview/src/Main.cxx @@ -0,0 +1,78 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "ApplicationCommon.h" + +#include <OSD_Environment.hxx> + +#include <Standard_WarningsDisable.hxx> +#include <QApplication> +#include <QCommandLineParser> +#include <QLocale> +#include <QSettings> +#include <QStringList> +#include <QTranslator> +#include <Standard_WarningsRestore.hxx> + +int main ( int argc, char* argv[] ) +{ + Q_INIT_RESOURCE(OCCTOverview); + + QApplication aQApp( argc, argv ); + + QSettings settings("OCCTOverview.conf", QSettings::IniFormat); + settings.beginGroup("ApplicationSetting"); + ApplicationType aCategory = static_cast<ApplicationType>(settings.value("ApplicationType", "").toInt()); + settings.endGroup(); + + ApplicationCommonWindow* aWindow = new ApplicationCommonWindow(aCategory); + QString aResName(":/icons/lamp.png"); + aWindow->setWindowIcon(QPixmap(aResName)); + + settings.beginGroup("WindowPosition"); + int x = settings.value("x", -1).toInt(); + int y = settings.value("y", -1).toInt(); + int width = settings.value("width", -1).toInt(); + int height = settings.value("height", -1).toInt(); + settings.endGroup(); + + if (x > 0 && y > 0 && width > 0 && height > 0) + { + aWindow->setGeometry(x, y, width, height); + } + aWindow->SetApplicationType(aCategory); + + aWindow->show(); + int aResult = aQApp.exec(); + + settings.beginGroup("WindowPosition"); + settings.setValue("x", aWindow->x()); + settings.setValue("y", aWindow->y()); + settings.setValue("width", aWindow->width()); + settings.setValue("height", aWindow->height()); + settings.endGroup(); + + settings.beginGroup("ApplicationSetting"); + settings.setValue("ApplicationType", aWindow->GetApplicationType()); + settings.endGroup(); + + return aResult; +} diff --git a/samples/qt/OCCTOverview/src/OCCTOverview.qrc b/samples/qt/OCCTOverview/src/OCCTOverview.qrc new file mode 100644 index 0000000000..8516659917 --- /dev/null +++ b/samples/qt/OCCTOverview/src/OCCTOverview.qrc @@ -0,0 +1,29 @@ +<RCC> + <qresource prefix="/icons"> + <file alias="lamp.png">../res/lamp.png</file> + <file alias="view_axo.png">../res/view_axo.png</file> + <file alias="view_back.png">../res/view_back.png</file> + <file alias="view_bottom.png">../res/view_bottom.png</file> + <file alias="view_comp_off.png">../res/view_comp_off.png</file> + <file alias="view_comp_on.png">../res/view_comp_on.png</file> + <file alias="view_fitall.png">../res/view_fitall.png</file> + <file alias="view_front.png">../res/view_front.png</file> + <file alias="view_left.png">../res/view_left.png</file> + <file alias="view_reset.png">../res/view_reset.png</file> + <file alias="view_top.png">../res/view_top.png</file> + <file alias="antialiasing.png">../res/antialiasing.png</file> + <file alias="raytracing.png">../res/raytracing.png</file> + <file alias="reflections.png">../res/reflections.png</file> + <file alias="shadows.png">../res/shadows.png</file> + <file alias="view_right.png">../res/view_right.png</file> + <file alias="tool_material.png">../res/tool_material.png</file> + <file alias="tool_color.png">../res/tool_color.png</file> + <file alias="tool_delete.png">../res/tool_delete.png</file> + <file alias="tool_shading.png">../res/tool_shading.png</file> + <file alias="tool_transparency.png">../res/tool_transparency.png</file> + <file alias="tool_wireframe.png">../res/tool_wireframe.png</file> + <file alias="help.png">../res/help.png</file> + <file alias="cursor_rotate.png">../res/cursor_rotate.png</file> + <file alias="cursor_zoom.png">../res/cursor_zoom.png</file> + </qresource> +</RCC> diff --git a/samples/qt/OCCTOverview/src/OcctHighlighter.cxx b/samples/qt/OCCTOverview/src/OcctHighlighter.cxx new file mode 100644 index 0000000000..d9d00122f4 --- /dev/null +++ b/samples/qt/OCCTOverview/src/OcctHighlighter.cxx @@ -0,0 +1,254 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "OcctHighlighter.h" + +#include <Standard_WarningsDisable.hxx> +#include <QFont> +#include <Standard_WarningsRestore.hxx> + +static const QString anOcctPatterns[] = +{ + QStringLiteral("gp_Pnt"), QStringLiteral("gp_XYZ"), QStringLiteral("gp_Vec"), + QStringLiteral("gp_Dir"), QStringLiteral("gp_Ax1"), QStringLiteral("gp_Ax2"), + QStringLiteral("gp_Ax3"), QStringLiteral("gp_Lin"), QStringLiteral("gp_Circ"), + QStringLiteral("gp_Elips"), QStringLiteral("gp_Parab"), QStringLiteral("gp_Hypr"), + QStringLiteral("gp_Cylinder"), QStringLiteral("gp_Cone"), QStringLiteral("gp_Sphere"), + QStringLiteral("gp_Torus"), QStringLiteral("gp_Pnt2d"), QStringLiteral("gp_XY"), + QStringLiteral("gp_Ax2d"), QStringLiteral("gp_Ax22d"), QStringLiteral("gp_Lin2d"), + QStringLiteral("gp_Circ2d."), QStringLiteral("gp_Elips2d"), QStringLiteral("gp_Parab2d"), + QStringLiteral("gp_Hypr2d"), QStringLiteral("Geom2d_BSplineCurve"), QStringLiteral("Geom2d_BezierCurve"), + QStringLiteral("Geom2d_OffsetCurve"), QStringLiteral("ProjLib"), QStringLiteral("ElSLib"), + QStringLiteral("Extrema_ExtElCS"), QStringLiteral("Extrema_POnCurv"), QStringLiteral("IntAna_Quadric"), + QStringLiteral("IntAna_IntConicQuad"), QStringLiteral("GccAna_Lin2d2Tan"), QStringLiteral("GccEnt_QualifiedCirc"), + QStringLiteral("Geom2dAPI_ProjectPointOnCurve"), QStringLiteral("Geom2dAPI_ExtremaCurveCurve"), + QStringLiteral("Geom2dAPI_InterCurveCurve"), QStringLiteral("Geom2dAPI_PointsToBSpline"), + QStringLiteral("Geom_CartesianPoint"), QStringLiteral("Geom_VectorWithMagnitude"), QStringLiteral("Geom_Axis1Placement"), + QStringLiteral("Geom_Axis2Placement"), QStringLiteral("Geom_Line"), QStringLiteral("Geom_Circle"), + QStringLiteral("Geom_Ellipse"), QStringLiteral("Geom_Parabola"), QStringLiteral("Geom_Hyperbola"), + QStringLiteral("Geom_BSplineCurve"), QStringLiteral("Geom_BezierCurve"), QStringLiteral("Geom_TrimmedCurve"), + QStringLiteral("Geom_OffsetCurve"), QStringLiteral("Geom_BSplineSurface"), QStringLiteral("Geom_BezierSurface"), + QStringLiteral("Geom_Plane"), QStringLiteral("Geom_CylindricalSurface"), QStringLiteral("Geom_ConicalSurface"), + QStringLiteral("Geom_SphericalSurface"), QStringLiteral("Geom_ToroidalSurface"), QStringLiteral("Geom_RectangularTrimmedSurface"), + QStringLiteral("Geom_OffsetSurface"), QStringLiteral("Geom_SurfaceOfLinearExtrusion"), QStringLiteral("Geom_SurfaceOfRevolution"), + QStringLiteral("BndLib_Add3dCurve"), QStringLiteral("BndLib_AddSurface"), QStringLiteral("GeomAdaptor_Curve"), + QStringLiteral("GeomAdaptor_Surface"), QStringLiteral("GeomAPI_PointsToBSpline"), QStringLiteral("GeomAPI_PointsToBSplineSurface"), + QStringLiteral("GeomConvert"), QStringLiteral("Geom2d_CartesianPoint"), QStringLiteral("Geom2d_VectorWithMagnitude"), + QStringLiteral("Geom2d_Line"), QStringLiteral("Geom2d_Circle"), QStringLiteral("Geom2d_Ellipse"), + QStringLiteral("Geom2d_Parabola"), QStringLiteral("Geom2d_Hyperbola"), QStringLiteral("Geom2d_TrimmedCurve"), + QStringLiteral("Geom2dAdaptor_Curve"), QStringLiteral("Bnd_Box2d"), QStringLiteral("BndLib_Add2dCurve"), + QStringLiteral("Adaptor2d_Curve2d"), QStringLiteral("BRepBuilderAPI_MakeEdge"), QStringLiteral("BRepBuilderAPI_MakeFace"), + QStringLiteral("BRepPrimAPI_MakeBox"), QStringLiteral("AIS_Point"), QStringLiteral("AIS_TextLabel"), QStringLiteral("AIS_Axis"), + QStringLiteral("AIS_Circle"), QStringLiteral("AIS_Plane"), QStringLiteral("AIS_Shape"), QStringLiteral("AIS_ColoredShape"), + QStringLiteral("GProp_PEquation"), QStringLiteral("Extrema_ExtCS"), QStringLiteral("GCPnts_QuasiUniformDeflection"), + QStringLiteral("GProp_GProps"), QStringLiteral("GProp_PrincipalProps"), QStringLiteral("TopoDS"), + QStringLiteral("TopoDS_Iterator"), QStringLiteral("TopoDS_Compound"), QStringLiteral("TopoDS_Edge"), QStringLiteral("TopoDS_Face"), + QStringLiteral("TopoDS_Shell"), QStringLiteral("TopoDS_Solid"), QStringLiteral("TopoDS_Vertex"), + QStringLiteral("TopoDS_Wire"), QStringLiteral("TopExp"), QStringLiteral("TopExp_Explorer"), + QStringLiteral("TColgp_Array2OfPnt"), QStringLiteral("BRep_Builder"), QStringLiteral("BRepGProp"), QStringLiteral("BRep_Tool"), + QStringLiteral("BRepTools"), QStringLiteral("BRepTools_ReShape"), QStringLiteral("BRepAdaptor_Curve"), + QStringLiteral("BRepAdaptor_CompCurve"), QStringLiteral("BRepAdaptor_Surface"), QStringLiteral("BRepAlgoAPI_Common"), + QStringLiteral("BRepAlgoAPI_Cut"), QStringLiteral("BRepAlgoAPI_Fuse"), QStringLiteral("BRepAlgoAPI_Section"), + QStringLiteral("BRepAlgoAPI_Splitter"), QStringLiteral("BRepAlgoAPI_Defeaturing"), QStringLiteral("BRepBuilderAPI_Copy"), + QStringLiteral("BRepBuilderAPI_MakeVertex"), QStringLiteral("BRepBuilderAPI_MakeEdge"), QStringLiteral("BRepBuilderAPI_MakeFace"), + QStringLiteral("BRepBuilderAPI_MakePolygon"), QStringLiteral("BRepBuilderAPI_MakeShell"), QStringLiteral("BRepBuilderAPI_MakeSolid"), + QStringLiteral("BRepBuilderAPI_MakeWire"), QStringLiteral("BRepBuilderAPI_NurbsConvert"), QStringLiteral("BRepBuilderAPI_Sewing"), + QStringLiteral("BRepBuilderAPI_Transform"), QStringLiteral("BRepCheck_Analyzer"), QStringLiteral("BRepPrimAPI_MakeBox"), + QStringLiteral("BRepPrimAPI_MakeCylinder"), QStringLiteral("BRepPrimAPI_MakeRevol"), QStringLiteral("BRepFilletAPI_MakeChamfer"), + QStringLiteral("BRepFilletAPI_MakeFillet"), QStringLiteral("BRepOffsetAPI_MakeOffset"), QStringLiteral("BRepOffsetAPI_MakeEvolved.hxx"), + QStringLiteral("Standard_Integer"), QStringLiteral("Standard_Real"), QStringLiteral("Standard_Boolean"), QStringLiteral("Standard_ShortReal"), + QStringLiteral("Standard_Character"), QStringLiteral("Standard_Byte"), QStringLiteral("Standard_Address"), QStringLiteral("Standard_Size"), + QStringLiteral("Standard_Time"), QStringLiteral("Standard_Utf8Char"), QStringLiteral("Standard_Utf8UChar"), + QStringLiteral("Standard_ExtCharacter"), QStringLiteral("Standard_Utf16Char"), QStringLiteral("Standard_Utf32Char"), + QStringLiteral("Standard_WideChar"), QStringLiteral("Standard_CString"), QStringLiteral("Standard_ExtString"), + QStringLiteral("NCollection_Vector"), QStringLiteral("TCollection_AsciiString"), QStringLiteral("TCollection_BaseSequence"), + QStringLiteral("TCollection_BasicMap"), QStringLiteral("TCollection_BasicMapIterator"), QStringLiteral("TCollection_ExtendedString"), + QStringLiteral("TCollection_HAsciiString"), QStringLiteral("TCollection_HExtendedString"), QStringLiteral("TCollection_MapNode"), + QStringLiteral("TCollection_MapNodePtr"), QStringLiteral("TCollection_SeqNode"), QStringLiteral("TCollection_SeqNodePtr"), + QStringLiteral("TCollection_Side"), QStringLiteral("Standard_False"), QStringLiteral("Standard_True"), + QStringLiteral("TCollection"), QStringLiteral("NCollection"), QStringLiteral("gp_Trsf"), QStringLiteral("Handle"), + QStringLiteral("Aspect_TOL_DASH"), QStringLiteral("Aspect_TOM_O_STAR"), QStringLiteral("Aspect_TOL_SOLID"), + QStringLiteral("Aspect_TOM_O_STAR"), QStringLiteral("AIS_InteractiveObject"), QStringLiteral("AIS_ListOfInteractive"), + QStringLiteral("Aspect_GDM_Lines"), QStringLiteral("Aspect_GDM_Points"), QStringLiteral("Aspect_TOM_POINT"), + QStringLiteral("Aspect_TOM_RING1"), QStringLiteral("Aspect_TOM_O"),QStringLiteral("BinDrivers"), + QStringLiteral("DefineFormat"), QStringLiteral("Font_FA_Bold"), QStringLiteral("Font_FA_BoldItalic"), + QStringLiteral("Font_FA_Italic"), QStringLiteral("Font_FA_Regular"), QStringLiteral("DownCast"), + QStringLiteral("gp_Pln"), QStringLiteral("Graphic3d_AspectMarker3d"), QStringLiteral("Graphic3d_HTA_LEFT"), + QStringLiteral("Graphic3d_NameOfMaterial"), QStringLiteral("Graphic3d_NOM_BRONZE"), QStringLiteral("Graphic3d_NOM_PLASTIC"), + QStringLiteral("Graphic3d_VTA_BOTTOM"), QStringLiteral("OpenGl_GraphicDriver"), QStringLiteral("PCDM_RS_OK"), + QStringLiteral("PCDM_SS_OK"), QStringLiteral("PCDM_ReaderStatus"), QStringLiteral("PCDM_StoreStatus"), + QStringLiteral("Prs3d_Drawer"), QStringLiteral("TPrsStd_AISPresentation"), QStringLiteral("Quantity_Color"), + QStringLiteral("Quantity_NameOfColor"), QStringLiteral("Quantity_NOC_BLUE1"), QStringLiteral("Quantity_NOC_CADETBLUE"), + QStringLiteral("Quantity_NOC_GREEN"), QStringLiteral("Quantity_NOC_MAGENTA1"), QStringLiteral("Quantity_NOC_RED"), + QStringLiteral("Quantity_NOC_YELLOW"), QStringLiteral("Quantity_NOC_WHITE"), QStringLiteral("Quantity_NOC_MATRABLUE"), + QStringLiteral("Quantity_TOC_RGB"), QStringLiteral("Quantity_TOC_HLS"), QStringLiteral("Standard_GUID"), + QStringLiteral("TColStd_ListIteratorOfListOfTransient"), QStringLiteral("TColStd_ListOfTransient"), QStringLiteral("TDataStd_Integer"), + QStringLiteral("TDataStd_Name"), QStringLiteral("TDataStd_Real"), QStringLiteral("TFunction_Driver"), + QStringLiteral("TFunction_DriverTable"), QStringLiteral("TFunction_Function"), QStringLiteral("TFunction_Logbook"), + QStringLiteral("TDF_Label"), QStringLiteral("TDF_TagSource"), QStringLiteral("TNaming_NamedShape"), + QStringLiteral("TopAbs_EDGE"), QStringLiteral("TopAbs_FACE"), QStringLiteral("TopAbs_VERTEX"), + QStringLiteral("TPrsStd_AISPresentation"), QStringLiteral("TPrsStd_AISViewer"), QStringLiteral("V3d_AmbientLight"), + QStringLiteral("V3d_DirectionalLight"), QStringLiteral("V3d_PositionalLight"), QStringLiteral("V3d_SpotLight"), + QStringLiteral("XmlDrivers") +}; + +static const QString aHelperPatterns[] = +{ + QStringLiteral("AdaptorCurve_AIS"), QStringLiteral("AdaptorVec_AIS"), QStringLiteral("AdaptorCurve2d_AIS"), + QStringLiteral("AdaptorPnt2d_AIS"), QStringLiteral("Sample2D_Image"), QStringLiteral("Sample2D_Markers"), + QStringLiteral("Sample2D_Face"), QStringLiteral("TOcafFunction_BoxDriver"), QStringLiteral("TOcafFunction_CylDriver"), + QStringLiteral("DisplayPresentation") +}; + +static const QString aKeywordPatterns[] = +{ + QStringLiteral("\\balignas\\b"), QStringLiteral("\\balignof\\b"), QStringLiteral("\\band\\b"), + QStringLiteral("\\band_eq\\b"), QStringLiteral("\\basm\\b"), QStringLiteral("\\bauto\\b"), + QStringLiteral("\\bbitand\\b"), QStringLiteral("\\bbitor\\b"), QStringLiteral("\\bbool\\b"), + QStringLiteral("\\bbreak\\b"), QStringLiteral("\\bcase\\b"), QStringLiteral("\\bcatch\\b"), + QStringLiteral("\\bchar\\b"), QStringLiteral("\\bchar16_t\\b"), QStringLiteral("\\bchar32_t\\b"), + QStringLiteral("\\bclass\\b"), QStringLiteral("\\bcompl\\b"), QStringLiteral("\\bconst\\b"), + QStringLiteral("\\bconstexpr\\b"), QStringLiteral("\\bconst_cast\\b"), QStringLiteral("\\bcontinue\\b"), + QStringLiteral("\\bdecltype\\b"), QStringLiteral("\\bdefault\\b"), QStringLiteral("\\bdelete\\b"), + QStringLiteral("\\bdo\\b"), QStringLiteral("\\bdouble\\b"), QStringLiteral("\\bdynamic_cast\\b"), + QStringLiteral("\\belse\\b"), QStringLiteral("\\benum\\b"), QStringLiteral("\\bexplicit\\b"), + QStringLiteral("\\bexport\\b"), QStringLiteral("\\bextern\\b"), QStringLiteral("\\bfalse\\b"), + QStringLiteral("\\bfloat\\b"), QStringLiteral("\\bfor\\b"), QStringLiteral("\\bfriend\\b"), + QStringLiteral("\\bgoto\\b"), QStringLiteral("\\bif\\b"), QStringLiteral("\\binline\\b"), + QStringLiteral("\\bint\\b"), QStringLiteral("\\blong\\b"), QStringLiteral("\\bmutable\\b"), + QStringLiteral("\\bnamespace\\b"), QStringLiteral("\\bnew\\b"), QStringLiteral("\\bnoexcept\\b"), + QStringLiteral("\\bnot\\b"), QStringLiteral("\\bnot_eq\\b"), QStringLiteral("\\bnullptr\\b"), + QStringLiteral("\\boperator\\b"), QStringLiteral("\\bor\\b"), QStringLiteral("\\bor_eq\\b"), + QStringLiteral("\\bprivate\\b"), QStringLiteral("\\bprotected\\b"), QStringLiteral("\\bpublic\\b"), + QStringLiteral("\\bregister\\b"), QStringLiteral("\\breinterpret_cast\\b"), QStringLiteral("\\breturn\\b"), + QStringLiteral("\\bshort\\b"), QStringLiteral("\\bsigned\\b"), QStringLiteral("\\bsizeof\\b"), + QStringLiteral("\\bstatic\\b"), QStringLiteral("\\bstatic_assert\\b"), QStringLiteral("\\bstatic_cast\\b"), + QStringLiteral("\\bstruct\\b"),QStringLiteral("\\bswitch\\b"), QStringLiteral("\\btemplate\\b"), + QStringLiteral("\\bthis\\b"), QStringLiteral("\\bthread_local\\b"), QStringLiteral("\\bthrow\\b"), + QStringLiteral("\\btrue\\b"), QStringLiteral("\\btry\\b"), QStringLiteral("\\btypedef\\b"), + QStringLiteral("\\btypeid\\b"), QStringLiteral("\\btypename\\b"),QStringLiteral("\\bunion\\b"), + QStringLiteral("\\bunsigned\\b"), QStringLiteral("\\busing\\b"), QStringLiteral("\\bvirtual\\b"), + QStringLiteral("\\bvoid\\b"), QStringLiteral("\\bvolatile\\b"), QStringLiteral("\\bwchar_t\\b"), + QStringLiteral("\\bwhile\\b"), QStringLiteral("\\bxor\\b"), QStringLiteral("\\bxor_eq\\b"), + QStringLiteral("\\boverride\\b"), QStringLiteral("\\bfinal\\b") +}; + +OcctHighlighter::OcctHighlighter(QTextDocument* theParent) +: QSyntaxHighlighter (theParent) +{ + HighlightingRule aRule; + + myOcctFormat.setForeground(Qt::darkCyan); + + for (const QString& aPattern : anOcctPatterns) + { + aRule.myPattern = QRegularExpression(aPattern); + aRule.myFormat = myOcctFormat; + myHighlightingRules.append(aRule); + } + + myHelperFormat.setForeground(Qt::red); + for (const QString& aPattern : aHelperPatterns) + { + aRule.myPattern = QRegularExpression(aPattern); + aRule.myFormat = myHelperFormat; + myHighlightingRules.append(aRule); + } + + + myKeywordFormat.setForeground(Qt::darkBlue); + myKeywordFormat.setFontWeight(QFont::Bold); + for (const QString& aPattern : aKeywordPatterns) + { + aRule.myPattern = QRegularExpression(aPattern); + aRule.myFormat = myKeywordFormat; + myHighlightingRules.append(aRule); + } + + myMemberFormat.setFontWeight(QFont::Bold); + aRule.myPattern = QRegularExpression(QStringLiteral("\\bmy[0-9A-Za-z]+\\b")); + aRule.myFormat = myMemberFormat; + myHighlightingRules.append(aRule); + + myLocalFormat.setForeground(Qt::darkMagenta); + aRule.myPattern = QRegularExpression(QStringLiteral("\\ba[0-9A-Za-z]+\\b")); + aRule.myFormat = myLocalFormat; + myHighlightingRules.append(aRule); + + myQuotationFormat.setForeground(Qt::darkRed); + aRule.myPattern = QRegularExpression(QStringLiteral("\".*\"")); + aRule.myFormat = myQuotationFormat; + myHighlightingRules.append(aRule); + + myFunctionFormat.setFontItalic(true); + myFunctionFormat.setForeground(Qt::blue); + aRule.myPattern = QRegularExpression(QStringLiteral("\\b[A-Za-z0-9_]+(?=\\()")); + aRule.myFormat = myFunctionFormat; + myHighlightingRules.append(aRule); + + mySingleLineCommentFormat.setForeground(Qt::darkGreen); + aRule.myPattern = QRegularExpression(QStringLiteral("//[^\n]*")); + aRule.myFormat = mySingleLineCommentFormat; + myHighlightingRules.append(aRule); + + myMultiLineCommentFormat.setForeground(Qt::darkGreen); + + myCommentStartExpression = QRegularExpression(QStringLiteral("/\\*")); + myCommentEndExpression = QRegularExpression(QStringLiteral("\\*/")); +} + +void OcctHighlighter::highlightBlock (const QString& theText) +{ + for (const HighlightingRule& rule : qAsConst(myHighlightingRules)) + { + QRegularExpressionMatchIterator matchIterator = rule.myPattern.globalMatch(theText); + while (matchIterator.hasNext()) + { + QRegularExpressionMatch match = matchIterator.next(); + setFormat(match.capturedStart(), match.capturedLength(), rule.myFormat); + } + } + + setCurrentBlockState(0); + + int startIndex = 0; + if (previousBlockState() != 1) + startIndex = theText.indexOf(myCommentStartExpression); + + while (startIndex >= 0) + { + QRegularExpressionMatch match = myCommentEndExpression.match(theText, startIndex); + int endIndex = match.capturedStart(); + int commentLength = 0; + if (endIndex == -1) + { + setCurrentBlockState(1); + commentLength = theText.length() - startIndex; + } + else + { + commentLength = endIndex - startIndex + + match.capturedLength(); + } + setFormat(startIndex, commentLength, myMultiLineCommentFormat); + startIndex = theText.indexOf(myCommentStartExpression, startIndex + commentLength); + } +} diff --git a/samples/qt/OCCTOverview/src/OcctHighlighter.h b/samples/qt/OCCTOverview/src/OcctHighlighter.h new file mode 100644 index 0000000000..0f74282f0b --- /dev/null +++ b/samples/qt/OCCTOverview/src/OcctHighlighter.h @@ -0,0 +1,75 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef OCCTHIGHLIGHTER_H +#define OCCTHIGHLIGHTER_H + +#include <Standard_Macro.hxx> + +#include <Standard_WarningsDisable.hxx> +#include <QRegularExpression> +#include <QSyntaxHighlighter> +#include <QString> +#include <QTextDocument> +#include <QTextCharFormat> +#include <Standard_WarningsRestore.hxx> + +QT_BEGIN_NAMESPACE +class QTextDocument; +QT_END_NAMESPACE + +//! Implements C++ and OCCT objects syntax +//! highlighting for sample code window +class OcctHighlighter: public QSyntaxHighlighter +{ + Q_OBJECT +public: + + OcctHighlighter(QTextDocument* theParent = 0); + +protected: + void highlightBlock(const QString& theText) Standard_OVERRIDE; + +private: + struct HighlightingRule + { + QRegularExpression myPattern; + QTextCharFormat myFormat; + }; + +private: + QVector<HighlightingRule> myHighlightingRules; + + QRegularExpression myCommentStartExpression; + QRegularExpression myCommentEndExpression; + + QTextCharFormat myKeywordFormat; + QTextCharFormat mySingleLineCommentFormat; + QTextCharFormat myMultiLineCommentFormat; + QTextCharFormat myQuotationFormat; + QTextCharFormat myFunctionFormat; + QTextCharFormat myOcctFormat; + QTextCharFormat myMemberFormat; + QTextCharFormat myLocalFormat; + QTextCharFormat myHelperFormat; +}; + +#endif diff --git a/samples/qt/OCCTOverview/src/OcctWindow.cxx b/samples/qt/OCCTOverview/src/OcctWindow.cxx new file mode 100644 index 0000000000..64705deea6 --- /dev/null +++ b/samples/qt/OCCTOverview/src/OcctWindow.cxx @@ -0,0 +1,179 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "OcctWindow.h" + +IMPLEMENT_STANDARD_RTTIEXT(OcctWindow, Aspect_Window) + +// ======================================================================= +// function : OcctWindow +// purpose : +// ======================================================================= +OcctWindow::OcctWindow(QWidget* theWidget, const Quantity_NameOfColor theBackColor) +: myWidget (theWidget) +{ + SetBackground(theBackColor); + myXLeft = myWidget->rect().left(); + myYTop = myWidget->rect().top(); + myXRight = myWidget->rect().right(); + myYBottom = myWidget->rect().bottom(); +} + +// ======================================================================= +// function : NativeParentHandle +// purpose : +// ======================================================================= +Aspect_Drawable OcctWindow::NativeParentHandle() const +{ + QWidget* aParentWidget = myWidget->parentWidget(); + if (aParentWidget != NULL) + { + return (Aspect_Drawable)aParentWidget->winId(); + } + else + { + return 0; + } +} + +// ======================================================================= +// function : Map +// purpose : +// ======================================================================= +void OcctWindow::Map() const +{ + myWidget->show(); + myWidget->update(); +} + +// ======================================================================= +// function : Unmap +// purpose : +// ======================================================================= +void OcctWindow::Unmap() const +{ + myWidget->hide(); + myWidget->update(); +} + +// ======================================================================= +// function : DoResize +// purpose : +// ======================================================================= +Aspect_TypeOfResize OcctWindow::DoResize() +{ + int aMask = 0; + Aspect_TypeOfResize aMode = Aspect_TOR_UNKNOWN; + + if (!myWidget->isMinimized()) + { + if (Abs(myWidget->rect().left() - myXLeft) > 2) + { + aMask |= 1; + } + if (Abs(myWidget->rect().right() - myXRight) > 2) + { + aMask |= 2; + } + if (Abs(myWidget->rect().top() - myYTop) > 2) + { + aMask |= 4; + } + if (Abs(myWidget->rect().bottom() - myYBottom) > 2) + { + aMask |= 8; + } + + switch (aMask) + { + case 0: + aMode = Aspect_TOR_NO_BORDER; + break; + case 1: + aMode = Aspect_TOR_LEFT_BORDER; + break; + case 2: + aMode = Aspect_TOR_RIGHT_BORDER; + break; + case 4: + aMode = Aspect_TOR_TOP_BORDER; + break; + case 5: + aMode = Aspect_TOR_LEFT_AND_TOP_BORDER; + break; + case 6: + aMode = Aspect_TOR_TOP_AND_RIGHT_BORDER; + break; + case 8: + aMode = Aspect_TOR_BOTTOM_BORDER; + break; + case 9: + aMode = Aspect_TOR_BOTTOM_AND_LEFT_BORDER; + break; + case 10: + aMode = Aspect_TOR_RIGHT_AND_BOTTOM_BORDER; + break; + default: + break; + } // end switch + + *((Standard_Integer*)&myXLeft) = myWidget->rect().left(); + *((Standard_Integer*)&myXRight) = myWidget->rect().right(); + *((Standard_Integer*)&myYTop) = myWidget->rect().top(); + *((Standard_Integer*)&myYBottom) = myWidget->rect().bottom(); + } + + return aMode; +} + +// ======================================================================= +// function : Ratio +// purpose : +// ======================================================================= +Standard_Real OcctWindow::Ratio() const +{ + QRect aRect = myWidget->rect(); + return Standard_Real(aRect.right() - aRect.left()) / Standard_Real(aRect.bottom() - aRect.top()); +} + +// ======================================================================= +// function : Size +// purpose : +// ======================================================================= +void OcctWindow::Size(Standard_Integer& theWidth, Standard_Integer& theHeight) const +{ + QRect aRect = myWidget->rect(); + theWidth = aRect.width(); + theHeight = aRect.height(); +} + +// ======================================================================= +// function : Position +// purpose : +// ======================================================================= +void OcctWindow::Position(Standard_Integer& theX1, Standard_Integer& theY1, + Standard_Integer& theX2, Standard_Integer& theY2) const +{ + theX1 = myWidget->rect().left(); + theX2 = myWidget->rect().right(); + theY1 = myWidget->rect().top(); + theY2 = myWidget->rect().bottom(); +} diff --git a/samples/qt/OCCTOverview/src/OcctWindow.h b/samples/qt/OCCTOverview/src/OcctWindow.h new file mode 100644 index 0000000000..73ae4cb618 --- /dev/null +++ b/samples/qt/OCCTOverview/src/OcctWindow.h @@ -0,0 +1,111 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef OcctWindow_H +#define OcctWindow_H + +#include <Aspect_Window.hxx> + +#include <Standard_WarningsDisable.hxx> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +//! OcctWindow class implements Aspect_Window interface using Qt API +//! as a platform-independent source of window geometry information. +//! A similar class should be used instead of platform-specific OCCT +//! classes (WNT_Window, Xw_Window) in any Qt 5 application using OCCT +//! 3D visualization. +//! +//! With Qt 5, the requirement for a Qt-based application to rely fully +//! on Qt public API and stop using platform-specific APIs looks mandatory. +//! An example of this is changed QWidget event sequence: when a widget is +//! first shown on the screen, a resize event is generated before the +//! underlying native window is resized correctly, however the QWidget instance +//! already holds correct size information at that moment. The OCCT classes +//! acting as a source of window geometry for V3d_View class (WNT_Window, Xw_Window) +//! are no longer compatible with changed Qt behavior because they rely on +//! platform-specific API that cannot return correct window geometry information +//! in some cases. A reasonable solution is to provide a Qt-based implementation +//! of Aspect_Window interface at application level. +class OcctWindow : public Aspect_Window +{ + DEFINE_STANDARD_RTTIEXT(OcctWindow,Aspect_Window) +public: + + //! Constructor + OcctWindow( QWidget* theWidget, const Quantity_NameOfColor theBackColor = Quantity_NOC_MATRAGRAY ); + + //! Destructor + virtual ~OcctWindow() + { + myWidget = NULL; + } + + //! Returns native Window handle + virtual Aspect_Drawable NativeHandle() const Standard_OVERRIDE + { + return (Aspect_Drawable)myWidget->winId(); + } + + //! Returns parent of native Window handle. + virtual Aspect_Drawable NativeParentHandle() const Standard_OVERRIDE; + + //! Applies the resizing to the window <me> + virtual Aspect_TypeOfResize DoResize() Standard_OVERRIDE; + + //! Returns True if the window <me> is opened + //! and False if the window is closed. + virtual Standard_Boolean IsMapped() const Standard_OVERRIDE + { + return !(myWidget->isMinimized() || myWidget->isHidden()); + } + + //! Apply the mapping change to the window <me> + //! and returns TRUE if the window is mapped at screen. + virtual Standard_Boolean DoMapping() const Standard_OVERRIDE { return Standard_True; } + + //! Opens the window <me>. + virtual void Map() const Standard_OVERRIDE; + + //! Closes the window <me>. + virtual void Unmap() const Standard_OVERRIDE; + + virtual void Position( Standard_Integer& theX1, Standard_Integer& theY1, + Standard_Integer& theX2, Standard_Integer& theY2 ) const Standard_OVERRIDE; + + //! Returns The Window RATIO equal to the physical + //! WIDTH/HEIGHT dimensions. + virtual Standard_Real Ratio() const Standard_OVERRIDE; + + virtual void Size( Standard_Integer& theWidth, Standard_Integer& theHeight ) const Standard_OVERRIDE; + + virtual Aspect_FBConfig NativeFBConfig() const Standard_OVERRIDE { return NULL; } + +protected: + Standard_Integer myXLeft; + Standard_Integer myYTop; + Standard_Integer myXRight; + Standard_Integer myYBottom; + QWidget* myWidget; +}; + + +#endif // OcctWindow_H \ No newline at end of file diff --git a/samples/qt/OCCTOverview/src/TranslateDialog.cxx b/samples/qt/OCCTOverview/src/TranslateDialog.cxx new file mode 100644 index 0000000000..fdf0eef594 --- /dev/null +++ b/samples/qt/OCCTOverview/src/TranslateDialog.cxx @@ -0,0 +1,113 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "TranslateDialog.h" + +#include <Standard_WarningsDisable.hxx> +#include <QGridLayout> +#include <Standard_WarningsRestore.hxx> + +TranslateDialog::TranslateDialog(QWidget* parent, Qt::WindowFlags flags, bool modal) +: QFileDialog(parent, flags) +{ + setOption(QFileDialog::DontUseNativeDialog); + setModal(modal); + + QGridLayout* grid = ::qobject_cast<QGridLayout*>(layout()); + + if (grid) + { + QVBoxLayout *vbox = new QVBoxLayout; + + QWidget* paramGroup = new QWidget(this); + paramGroup->setLayout(vbox); + + myBox = new QComboBox(paramGroup); + vbox->addWidget(myBox); + + int row = grid->rowCount(); + grid->addWidget(paramGroup, row, 1, 1, 3); // make combobox occupy 1 row and 3 columns starting from 1 + } +} + +TranslateDialog::~TranslateDialog() +{ +} + +int TranslateDialog::getMode() const +{ + if (myBox->currentIndex() < 0 || myBox->currentIndex() > (int)myList.count() - 1) + { + return -1; + } + else + { + return myList.at(myBox->currentIndex()); + } +} + +void TranslateDialog::setMode(const int mode) +{ + int idx = myList.indexOf(mode); + if (idx >= 0) + { + myBox->setCurrentIndex(idx); + } +} + +void TranslateDialog::addMode(const int mode, const QString& name) +{ + myBox->show(); + myBox->addItem(name); + myList.append(mode); + myBox->updateGeometry(); + updateGeometry(); +} + +void TranslateDialog::clear() +{ + myList.clear(); + myBox->clear(); + myBox->hide(); + myBox->updateGeometry(); + updateGeometry(); +} + +QListView* TranslateDialog::findListView(const QObjectList & childList) +{ + QListView* listView = 0; + for (int i = 0, n = childList.count(); i < n && !listView; i++) + { + listView = qobject_cast<QListView*>(childList.at(i)); + if (!listView && childList.at(i)) + { + listView = findListView(childList.at(i)->children()); + } + } + return listView; +} + +void TranslateDialog::showEvent(QShowEvent* event) +{ + QFileDialog::showEvent(event); + QListView* aListView = findListView(children()); + aListView->setViewMode(QListView::ListMode); +} diff --git a/samples/qt/OCCTOverview/src/TranslateDialog.h b/samples/qt/OCCTOverview/src/TranslateDialog.h new file mode 100644 index 0000000000..df28094d96 --- /dev/null +++ b/samples/qt/OCCTOverview/src/TranslateDialog.h @@ -0,0 +1,56 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef TRANSLATEDIALOG_H +#define TRANSLATEDIALOG_H + +#include <Standard_WarningsDisable.hxx> +#include <QComboBox> +#include <QFileDialog> +#include <QList> +#include <QListView> +#include <QShowEvent> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +//! Qt file dialog for save and restore sample files +class TranslateDialog : public QFileDialog +{ +public: + TranslateDialog(QWidget* = 0, Qt::WindowFlags flags = 0, bool = true); + ~TranslateDialog(); + int getMode() const; + void setMode(const int); + void addMode(const int, const QString&); + void clear(); + +protected: + void showEvent(QShowEvent* event); + +private: + QListView* findListView(const QObjectList&); + +private: + QComboBox* myBox; + QList<int> myList; +}; + +#endif // TRANSLATEDIALOG_H diff --git a/samples/qt/OCCTOverview/src/Transparency.cxx b/samples/qt/OCCTOverview/src/Transparency.cxx new file mode 100644 index 0000000000..33fd02fc8e --- /dev/null +++ b/samples/qt/OCCTOverview/src/Transparency.cxx @@ -0,0 +1,46 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include "Transparency.h" + +#include <Standard_WarningsDisable.hxx> +#include <QHBoxLayout> +#include <QLabel> +#include <Standard_WarningsRestore.hxx> + +DialogTransparency::DialogTransparency(QWidget* parent) +: QDialog(parent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) +{ + setWindowTitle(tr("Transparency")); + QHBoxLayout* base = new QHBoxLayout(this); + + base->addWidget(new QLabel("0", this)); + + mySlider = new QSlider(Qt::Horizontal, this); + mySlider->setRange(0, 10); + mySlider->setTickPosition(QSlider::TicksBelow); + mySlider->setTickInterval(1); + mySlider->setPageStep(2); + base->addWidget(mySlider); + connect(mySlider, SIGNAL(valueChanged(int)), this, SIGNAL(sendTransparencyChanged(int))); + + base->addWidget(new QLabel("10", this)); +} diff --git a/samples/qt/OCCTOverview/src/Transparency.h b/samples/qt/OCCTOverview/src/Transparency.h new file mode 100644 index 0000000000..80409e1748 --- /dev/null +++ b/samples/qt/OCCTOverview/src/Transparency.h @@ -0,0 +1,55 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#include <Standard_WarningsDisable.hxx> +#include <QDialog> +#include <QSlider> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +#include <AIS_InteractiveContext.hxx> + +class QSlider; + +//! Qt dialog with slider for change shapes transparency +class DialogTransparency : public QDialog +{ + Q_OBJECT +public: + DialogTransparency ( QWidget * parent=0 ); + ~DialogTransparency() { } + + int value() const + { + return mySlider->value(); + } + + void setValue(int theVal) const + { + mySlider->setValue(theVal); + } + +signals: + void sendTransparencyChanged(int value); + +private: + QSlider* mySlider; +}; diff --git a/samples/qt/OCCTOverview/src/View.cxx b/samples/qt/OCCTOverview/src/View.cxx new file mode 100644 index 0000000000..e3235029e4 --- /dev/null +++ b/samples/qt/OCCTOverview/src/View.cxx @@ -0,0 +1,676 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#if !defined _WIN32 +#define QT_CLEAN_NAMESPACE /* avoid definition of INT32 and INT8 */ +#endif + +#include "View.h" + +#include "ApplicationCommon.h" +#include "OcctWindow.h" +#include "Transparency.h" + +#include <Standard_WarningsDisable.hxx> +#include <QApplication> +#include <QBoxLayout> +#include <QFileInfo> +#include <QFileDialog> +#include <QMouseEvent> +#include <QMdiSubWindow> +#include <QColorDialog> +#include <QCursor> +#include <QPainter> +#include <QStyleFactory> +#include <Standard_WarningsRestore.hxx> + +#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && QT_VERSION < 0x050000 +#include <QX11Info> +#endif + +#include <Aspect_DisplayConnection.hxx> +#include <Graphic3d_GraphicDriver.hxx> +#include <Graphic3d_TextureEnv.hxx> + +namespace +{ + //! Map Qt buttons bitmask to virtual keys. + static Aspect_VKeyMouse qtMouseButtons2VKeys(Qt::MouseButtons theButtons) + { + Aspect_VKeyMouse aButtons = Aspect_VKeyMouse_NONE; + if ((theButtons & Qt::LeftButton) != 0) + { + aButtons |= Aspect_VKeyMouse_LeftButton; + } + if ((theButtons & Qt::MiddleButton) != 0) + { + aButtons |= Aspect_VKeyMouse_MiddleButton; + } + if ((theButtons & Qt::RightButton) != 0) + { + aButtons |= Aspect_VKeyMouse_RightButton; + } + return aButtons; + } + + //! Map Qt mouse modifiers bitmask to virtual keys. + static Aspect_VKeyFlags qtMouseModifiers2VKeys(Qt::KeyboardModifiers theModifiers) + { + Aspect_VKeyFlags aFlags = Aspect_VKeyFlags_NONE; + if ((theModifiers & Qt::ShiftModifier) != 0) + { + aFlags |= Aspect_VKeyFlags_SHIFT; + } + if ((theModifiers & Qt::ControlModifier) != 0) + { + aFlags |= Aspect_VKeyFlags_CTRL; + } + if ((theModifiers & Qt::AltModifier) != 0) + { + aFlags |= Aspect_VKeyFlags_ALT; + } + return aFlags; + } + + static QCursor* defCursor = NULL; + static QCursor* handCursor = NULL; + static QCursor* panCursor = NULL; + static QCursor* globPanCursor = NULL; + static QCursor* zoomCursor = NULL; + static QCursor* rotCursor = NULL; + +} + +View::View (const Handle(AIS_InteractiveContext)& theContext, bool theIs3dView, QWidget* theParent) +: QWidget(theParent), + myIsRaytracing(false), + myIsShadowsEnabled(true), + myIsReflectionsEnabled(false), + myIsAntialiasingEnabled(false), + myIs3dView (theIs3dView), + myBackMenu(NULL) +{ +#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && QT_VERSION < 0x050000 + XSynchronize(x11Info().display(), true); +#endif + myContext = theContext; + myCurZoom = 0; + + setAttribute(Qt::WA_PaintOnScreen); + setAttribute(Qt::WA_NoSystemBackground); + + myDefaultGestures = myMouseGestureMap; + myCurrentMode = CurrentAction3d::Nothing; + setMouseTracking(true); + + initViewActions(); + initCursors(); + + setBackgroundRole(QPalette::NoRole);//NoBackground ); + // set focus policy to threat QContextMenuEvent from keyboard + setFocusPolicy(Qt::StrongFocus); + setAttribute(Qt::WA_PaintOnScreen); + setAttribute(Qt::WA_NoSystemBackground); + init(); +} + +void View::init() +{ + if (myV3dView.IsNull()) + { + myV3dView = myContext->CurrentViewer()->CreateView(); + } + + Handle(OcctWindow) hWnd = new OcctWindow(this); + myV3dView->SetWindow(hWnd); + if (!hWnd->IsMapped()) + { + hWnd->Map(); + } + + if (myIs3dView) + { + myV3dView->SetBackgroundColor(Quantity_Color(0.0, 0.0, 0.3, Quantity_TOC_RGB)); + } + else + { + myV3dView->SetBackgroundColor(Quantity_Color(0.0, 0.2, 0.0, Quantity_TOC_RGB)); + myV3dView->SetProj(V3d_Zpos); + } + + myV3dView->MustBeResized(); + + if (myIsRaytracing) + { + myV3dView->ChangeRenderingParams().Method = Graphic3d_RM_RAYTRACING; + } +} + +void View::paintEvent(QPaintEvent *) +{ + myV3dView->InvalidateImmediate(); + FlushViewEvents(myContext, myV3dView, true); +} + +void View::resizeEvent(QResizeEvent *) +{ + if (!myV3dView.IsNull()) + { + myV3dView->MustBeResized(); + } +} + +void View::OnSelectionChanged(const Handle(AIS_InteractiveContext)& theCtx, + const Handle(V3d_View)& theView) +{ + Q_UNUSED(theCtx) + Q_UNUSED(theView) +} + +void View::fitAll() +{ + myV3dView->FitAll(); + myV3dView->ZFitAll(); + myV3dView->Redraw(); +} + +void View::axo() +{ + if (myIs3dView) + { + myV3dView->SetProj(V3d_XposYnegZpos); + } +} + +void View::hlrOff() +{ + QApplication::setOverrideCursor(Qt::WaitCursor); + myV3dView->SetComputedMode(Standard_False); + myV3dView->Redraw(); + QAction* aShadingAction = getViewAction(ViewAction::Shading); + aShadingAction->setEnabled(true); + QAction* aWireframeAction = getViewAction(ViewAction::Wireframe); + aWireframeAction->setEnabled(true); + QApplication::restoreOverrideCursor(); +} + +void View::hlrOn() +{ + QApplication::setOverrideCursor(Qt::WaitCursor); + myV3dView->SetComputedMode(Standard_True); + myV3dView->Redraw(); + QAction* aShadingAction = getViewAction(ViewAction::Shading); + aShadingAction->setEnabled(false); + QAction* aWireframeAction = getViewAction(ViewAction::Wireframe); + aWireframeAction->setEnabled(false); + QApplication::restoreOverrideCursor(); +} + +void View::shading() +{ + myContext->SetDisplayMode(1, Standard_True); +} + +void View::wireframe() +{ + myContext->SetDisplayMode(0, Standard_True); +} + +void View::SetRaytracedShadows(bool theState) +{ + myV3dView->ChangeRenderingParams().IsShadowEnabled = theState; + myIsShadowsEnabled = theState; + myContext->UpdateCurrentViewer(); +} + +void View::SetRaytracedReflections(bool theState) +{ + myV3dView->ChangeRenderingParams().IsReflectionEnabled = theState; + myIsReflectionsEnabled = theState; + myContext->UpdateCurrentViewer(); +} + +void View::onRaytraceAction() +{ + QAction* aSentBy = (QAction*)sender(); + + if (aSentBy == myRaytraceActions.value(RaytraceAction::ToolRaytracing)) + { + bool aState = myRaytraceActions.value(RaytraceAction::ToolRaytracing)->isChecked(); + + QApplication::setOverrideCursor(Qt::WaitCursor); + if (aState) + EnableRaytracing(); + else + DisableRaytracing(); + QApplication::restoreOverrideCursor(); + } + + if (aSentBy == myRaytraceActions.value(RaytraceAction::ToolShadows)) + { + bool aState = myRaytraceActions.value(RaytraceAction::ToolShadows)->isChecked(); + SetRaytracedShadows(aState); + } + + if (aSentBy == myRaytraceActions.value(RaytraceAction::ToolReflections)) + { + bool aState = myRaytraceActions.value(RaytraceAction::ToolReflections)->isChecked(); + SetRaytracedReflections(aState); + } + + if (aSentBy == myRaytraceActions.value(RaytraceAction::ToolAntialiasing)) + { + bool aState = myRaytraceActions.value(RaytraceAction::ToolAntialiasing)->isChecked(); + SetRaytracedAntialiasing(aState); + } +} + +void View::SetRaytracedAntialiasing(bool theState) +{ + myV3dView->ChangeRenderingParams().IsAntialiasingEnabled = theState; + myIsAntialiasingEnabled = theState; + myContext->UpdateCurrentViewer(); +} + +void View::EnableRaytracing() +{ + if (!myIsRaytracing) + { + myV3dView->ChangeRenderingParams().Method = Graphic3d_RM_RAYTRACING; + } + myIsRaytracing = true; + myContext->UpdateCurrentViewer(); +} + +void View::DisableRaytracing() +{ + if (myIsRaytracing) + { + myV3dView->ChangeRenderingParams().Method = Graphic3d_RM_RASTERIZATION; + } + myIsRaytracing = false; + myContext->UpdateCurrentViewer(); +} + +void View::updateToggled(bool isOn) +{ + QAction* sentBy = (QAction*)sender(); + if (!isOn) + { + return; + } + + for (QAction* anAction : myViewActions) + { + if (anAction && (anAction != sentBy)) + { + anAction->setCheckable(true); + anAction->setChecked(false); + } + else + { + if (sentBy == myViewActions.value(ViewAction::FitArea)) + setCursor(*handCursor); + else if (sentBy == myViewActions.value(ViewAction::Zoom)) + setCursor(*zoomCursor); + else if (sentBy == myViewActions.value(ViewAction::Pan)) + setCursor(*panCursor); + else if (sentBy == myViewActions.value(ViewAction::GlobalPan)) + setCursor(*globPanCursor); + else if (sentBy == myViewActions.value(ViewAction::Rotation)) + setCursor(*rotCursor); + else + setCursor(*defCursor); + + sentBy->setCheckable(false); + } + } +} + +void View::initCursors() +{ + if (!defCursor) + defCursor = new QCursor(Qt::ArrowCursor); + if (!handCursor) + handCursor = new QCursor(Qt::PointingHandCursor); + if (!panCursor) + panCursor = new QCursor(Qt::SizeAllCursor); + if (!globPanCursor) + globPanCursor = new QCursor(Qt::CrossCursor); + if (!zoomCursor) + zoomCursor = new QCursor(QPixmap(":/icons/cursor_zoom.png")); + if (!rotCursor) + rotCursor = new QCursor(QPixmap(":/icons/cursor_rotate.png")); +} + +QList<QAction*> View::getViewActions() +{ + initViewActions(); + return myViewActions.values(); +} + +QList<QAction*> View::getRaytraceActions() +{ + initRaytraceActions(); + return myRaytraceActions.values(); +} + +QAction* View::getViewAction(ViewAction theAction) +{ + return myViewActions.value(theAction); +} + +QAction* View::getRaytraceAction(RaytraceAction theAction) +{ + return myRaytraceActions.value(theAction); +} + +/*! + Get paint engine for the OpenGL viewer. [ virtual public ] +*/ +QPaintEngine* View::paintEngine() const +{ + return 0; +} + +QAction* View::RegisterAction(QString theIconPath, QString thePromt, void (View::*theSlot)(void)) +{ + QAction* anAction = new QAction(QPixmap(theIconPath), thePromt, this); + anAction->setToolTip(thePromt); + anAction->setStatusTip(thePromt); + connect(anAction, &QAction::triggered, this, theSlot); + return anAction; +} + +void View::initViewActions() +{ + if (!myViewActions.empty()) + return; + myViewActions[ViewAction::FitAll] = RegisterAction(":/icons/view_fitall.png", tr("Fit all"), &View::fitAll); + if (myIs3dView) + { + myViewActions[ViewAction::Axo] = RegisterAction(":/icons/view_axo.png", tr("Isometric"), &View::axo); + + QActionGroup* aShadingActionGroup = new QActionGroup(this); + QAction* aShadingAction = RegisterAction(":/icons/tool_shading.png", tr("Shading"), &View::shading); + aShadingAction->setCheckable(true); + aShadingActionGroup->addAction(aShadingAction); + myViewActions[ViewAction::Shading] = aShadingAction; + + QAction* aWireframeAction = RegisterAction(":/icons/tool_wireframe.png", tr("Wireframe"), &View::wireframe); + aWireframeAction->setCheckable(true); + aShadingActionGroup->addAction(aWireframeAction); + myViewActions[ViewAction::Wireframe] = aWireframeAction; + + QActionGroup* aHlrActionGroup = new QActionGroup(this); + QAction* aHlrOffAction = RegisterAction(":/icons/view_comp_off.png", tr("HLR off"), &View::hlrOff); + aHlrOffAction->setCheckable(true); + aHlrActionGroup->addAction(aHlrOffAction); + myViewActions[ViewAction::HlrOff] = aHlrOffAction; + + QAction* aHlrOnAction = RegisterAction(":/icons/view_comp_on.png", tr("HLR on"), &View::hlrOn); + aHlrOnAction->setCheckable(true); + aHlrActionGroup->addAction(aHlrOnAction); + myViewActions[ViewAction::HlrOn] = aHlrOnAction; + + myViewActions[ViewAction::Transparency] = RegisterAction(":/icons/tool_transparency.png", tr("Transparency"), &View::onTransparency); + } +} + +void View::initRaytraceActions() +{ + if (!myRaytraceActions.empty()) + { + return; + } + + QAction* aRayTraceAction = RegisterAction(":/icons/raytracing.png", tr("Ray-tracing"), &View::onRaytraceAction); + myRaytraceActions[RaytraceAction::ToolRaytracing] = aRayTraceAction; + aRayTraceAction->setCheckable(true); + aRayTraceAction->setChecked(false); + + QAction* aShadowAction = RegisterAction(":/icons/shadows.png", tr("Shadows"), &View::onRaytraceAction); + myRaytraceActions[RaytraceAction::ToolShadows] = aShadowAction; + aShadowAction->setCheckable(true); + aShadowAction->setChecked(true); + + QAction* aReflectAction = RegisterAction(":/icons/reflections.png", tr("Reflections"), &View::onRaytraceAction); + myRaytraceActions[RaytraceAction::ToolReflections] = aReflectAction; + aReflectAction->setCheckable(true); + aReflectAction->setChecked(false); + + QAction* anAntiAliasingAction = RegisterAction(":/icons/antialiasing.png", tr("Anti-aliasing"), &View::onRaytraceAction); + myRaytraceActions[RaytraceAction::ToolAntialiasing] = anAntiAliasingAction; + anAntiAliasingAction->setCheckable(true); + anAntiAliasingAction->setChecked(false); +} + +void View::activateCursor(const CurrentAction3d theMode) +{ + QCursor* aCursor = defCursor; + switch (theMode) + { + case CurrentAction3d::DynamicPanning: aCursor = panCursor; break; + case CurrentAction3d::DynamicZooming: aCursor = zoomCursor; break; + case CurrentAction3d::DynamicRotation: aCursor = rotCursor; break; + case CurrentAction3d::GlobalPanning: aCursor = globPanCursor; break; + case CurrentAction3d::WindowZooming: aCursor = handCursor; break; + case CurrentAction3d::Nothing: aCursor = defCursor; break; + default: + break; + } + setCursor(*aCursor); +} + +void View::mousePressEvent(QMouseEvent* theEvent) +{ + Qt::MouseButtons aMouseButtons = theEvent->buttons(); + if (!myIs3dView) + { + aMouseButtons.setFlag(Qt::LeftButton, false); + } + const Graphic3d_Vec2i aPnt(theEvent->pos().x(), theEvent->pos().y()); + const Aspect_VKeyFlags aFlags = qtMouseModifiers2VKeys(theEvent->modifiers()); + if (!myV3dView.IsNull() + && UpdateMouseButtons(aPnt, qtMouseButtons2VKeys(aMouseButtons), aFlags, false)) + { + updateView(); + } + myClickPos = aPnt; +} + +void View::mouseReleaseEvent(QMouseEvent* theEvent) +{ + Qt::MouseButtons aMouseButtons = theEvent->buttons(); + if (!myIs3dView) + { + aMouseButtons.setFlag(Qt::LeftButton, false); + } + const Graphic3d_Vec2i aPnt(theEvent->pos().x(), theEvent->pos().y()); + const Aspect_VKeyFlags aFlags = qtMouseModifiers2VKeys(theEvent->modifiers()); + if (!myV3dView.IsNull() + && UpdateMouseButtons(aPnt, qtMouseButtons2VKeys(aMouseButtons), aFlags, false)) + { + updateView(); + } + + if (myCurrentMode == CurrentAction3d::GlobalPanning) + { + myV3dView->Place(aPnt.x(), aPnt.y(), myCurZoom); + } + if (myCurrentMode != CurrentAction3d::Nothing) + { + setCurrentAction(CurrentAction3d::Nothing); + } +} + +void View::mouseMoveEvent(QMouseEvent* theEvent) +{ + Qt::MouseButtons aMouseButtons = theEvent->buttons(); + if (!myIs3dView) + { + aMouseButtons.setFlag(Qt::LeftButton, false); + } + const Graphic3d_Vec2i aNewPos(theEvent->pos().x(), theEvent->pos().y()); + if (!myV3dView.IsNull() + && UpdateMousePosition(aNewPos, qtMouseButtons2VKeys(aMouseButtons), qtMouseModifiers2VKeys(theEvent->modifiers()), false)) + { + updateView(); + } +} + +//============================================================================== +//function : wheelEvent +//purpose : +//============================================================================== +void View::wheelEvent(QWheelEvent* theEvent) +{ + const Graphic3d_Vec2i aPos(theEvent->pos().x(), theEvent->pos().y()); + if (!myV3dView.IsNull() + && UpdateZoom(Aspect_ScrollDelta(aPos, theEvent->delta() / 8))) + { + updateView(); + } +} + +// ======================================================================= +// function : updateView +// purpose : +// ======================================================================= +void View::updateView() +{ + update(); +} + +void View::defineMouseGestures() +{ + myMouseGestureMap.Clear(); + AIS_MouseGesture aRot = AIS_MouseGesture_RotateOrbit; + activateCursor(myCurrentMode); + switch (myCurrentMode) + { + case CurrentAction3d::Nothing: + { + myMouseGestureMap = myDefaultGestures; + break; + } + case CurrentAction3d::DynamicZooming: + { + myMouseGestureMap.Bind(Aspect_VKeyMouse_LeftButton, AIS_MouseGesture_Zoom); + break; + } + case CurrentAction3d::GlobalPanning: + { + break; + } + case CurrentAction3d::WindowZooming: + { + myMouseGestureMap.Bind(Aspect_VKeyMouse_LeftButton, AIS_MouseGesture_ZoomWindow); + break; + } + case CurrentAction3d::DynamicPanning: + { + myMouseGestureMap.Bind(Aspect_VKeyMouse_LeftButton, AIS_MouseGesture_Pan); + break; + } + case CurrentAction3d::DynamicRotation: + { + myMouseGestureMap.Bind(Aspect_VKeyMouse_LeftButton, aRot); + break; + } + default: + { + break; + } + } +} + +void View::addItemInPopup(QMenu* theMenu) +{ + Q_UNUSED(theMenu) +} + +void View::onBackground() +{ + QColor aColor; + Standard_Real R1; + Standard_Real G1; + Standard_Real B1; + myV3dView->BackgroundColor(Quantity_TOC_RGB, R1, G1, B1); + aColor.setRgb((Standard_Integer)(R1 * 255), (Standard_Integer)(G1 * 255), (Standard_Integer)(B1 * 255)); + + QColor aRetColor = QColorDialog::getColor(aColor); + if (aRetColor.isValid()) + { + R1 = aRetColor.red() / 255.; + G1 = aRetColor.green() / 255.; + B1 = aRetColor.blue() / 255.; + myV3dView->SetBackgroundColor(Quantity_TOC_RGB, R1, G1, B1); + } + myV3dView->Redraw(); +} + +void View::onEnvironmentMap() +{ + if (myBackMenu->actions().at(1)->isChecked()) + { + QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", + tr("All Image Files (*.bmp *.gif *.jpg *.jpeg *.png *.tga)")); + + const TCollection_AsciiString anUtf8Path(fileName.toUtf8().data()); + Handle(Graphic3d_TextureEnv) aTexture = new Graphic3d_TextureEnv(anUtf8Path); + myV3dView->SetTextureEnv(aTexture); + } + else + { + myV3dView->SetTextureEnv(Handle(Graphic3d_TextureEnv)()); + } + + myV3dView->Redraw(); +} + +void View::onTransparency() +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + if (anAisObjectsList.Extent() == 0) + { + return; + } + + double aTranspValue = anAisObjectsList.First()->Transparency(); + DialogTransparency aDlg(this); + aDlg.setValue(int(aTranspValue * 10)); + connect(&aDlg, SIGNAL(sendTransparencyChanged(int)), SLOT(onTransparencyChanged(int))); + aDlg.exec(); +} + +void View::onTransparencyChanged(int theVal) +{ + AIS_ListOfInteractive anAisObjectsList; + myContext->DisplayedObjects(anAisObjectsList); + double aTranspValue = theVal / 10.; + for (Handle(AIS_InteractiveObject) anAisObject : anAisObjectsList) + { + myContext->SetTransparency(anAisObject, aTranspValue, Standard_False); + } + myContext->UpdateCurrentViewer(); +} diff --git a/samples/qt/OCCTOverview/src/View.h b/samples/qt/OCCTOverview/src/View.h new file mode 100644 index 0000000000..d21172358f --- /dev/null +++ b/samples/qt/OCCTOverview/src/View.h @@ -0,0 +1,169 @@ +// Copyright (c) 2020 OPEN CASCADE SAS +// +// This file is part of the examples of the Open CASCADE Technology software library. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE + +#ifndef VIEW_H +#define VIEW_H + +#include <functional> + +#include <Standard_WarningsDisable.hxx> +#include <QAction> +#include <QList> +#include <QMenu> +#include <QToolBar> +#include <QWidget> +#include <Standard_WarningsRestore.hxx> + +#include <AIS_InteractiveContext.hxx> +#include <AIS_ViewController.hxx> +#include <V3d_View.hxx> + +class TopoDS_Shape; + +enum CurrentAction3d { Nothing, DynamicZooming, WindowZooming, + DynamicPanning, GlobalPanning, DynamicRotation, ObjectDececting }; +enum ViewAction { FitAll, FitArea, Zoom, Pan, GlobalPan, Front, Back, Top, Bottom, + Left, Right, Axo, Rotation, Reset, HlrOff, HlrOn, Shading, Wireframe, Transparency }; +enum RaytraceAction { ToolRaytracing, ToolShadows, ToolReflections, ToolAntialiasing }; + +//! Qt widget containing V3d_View and toolbar with view manipulation buttons. +//! Also use AIS_ViewController for redirecting user input (mouse, keyboard) +//! into 3D viewer events (rotation, panning, zooming) +class View: public QWidget, protected AIS_ViewController +{ + Q_OBJECT +public: + View (const Handle(AIS_InteractiveContext)& theContext, bool theIs3dView, QWidget* theParent); + + ~View() + { + delete myBackMenu; + } + + virtual void init(); + QList<QAction*> getViewActions(); + QAction* getViewAction(ViewAction theAction); + QList<QAction*> getRaytraceActions(); + QAction* getRaytraceAction(RaytraceAction theAction); + + void EnableRaytracing(); + void DisableRaytracing(); + + void SetRaytracedShadows (bool theState); + void SetRaytracedReflections (bool theState); + void SetRaytracedAntialiasing (bool theState); + + bool IsRaytracingMode() const { return myIsRaytracing; } + bool IsShadowsEnabled() const { return myIsShadowsEnabled; } + bool IsReflectionsEnabled() const { return myIsReflectionsEnabled; } + bool IsAntialiasingEnabled() const { return myIsAntialiasingEnabled; } + + static QString GetMessages(int type,TopAbs_ShapeEnum aSubShapeType, TopAbs_ShapeEnum aShapeType); + static QString GetShapeType(TopAbs_ShapeEnum aShapeType); + + Standard_EXPORT static void OnButtonuseraction(int ExerciceSTEP, Handle(AIS_InteractiveContext)& ); + Standard_EXPORT static void DoSelection(int Id, Handle(AIS_InteractiveContext)& ); + Standard_EXPORT static void OnSetSelectionMode(Handle(AIS_InteractiveContext)&, + Standard_Integer&, + TopAbs_ShapeEnum& SelectionMode, + Standard_Boolean& ); + virtual QPaintEngine* paintEngine() const; + const Handle(V3d_View)& getView() const { return myV3dView; } +signals: + void selectionChanged(); + +public slots: + void fitAll(); + void axo(); + void hlrOn(); + void hlrOff(); + void shading(); + void wireframe(); + void onTransparency(); + + void updateToggled( bool ); + void onBackground(); + void onEnvironmentMap(); + void onRaytraceAction(); + +private slots: +void onTransparencyChanged(int theVal); + +protected: + virtual void paintEvent( QPaintEvent* ) Standard_OVERRIDE; + virtual void resizeEvent( QResizeEvent* ) Standard_OVERRIDE; + virtual void mousePressEvent( QMouseEvent* ) Standard_OVERRIDE; + virtual void mouseReleaseEvent(QMouseEvent* ) Standard_OVERRIDE; + virtual void mouseMoveEvent( QMouseEvent* ) Standard_OVERRIDE; + virtual void wheelEvent(QWheelEvent*) Standard_OVERRIDE; + + virtual void addItemInPopup( QMenu* ); + + Handle(AIS_InteractiveContext)& getContext() { return myContext; } + + void activateCursor( const CurrentAction3d ); + + CurrentAction3d getCurrentMode() const { return myCurrentMode; } + +private: + void initCursors(); + void initViewActions(); + void initRaytraceActions(); + + QAction* RegisterAction(QString theIconPath, QString thePromt, void (View::*theSlot)(void)); + +private: + bool myIsRaytracing; + bool myIsShadowsEnabled; + bool myIsReflectionsEnabled; + bool myIsAntialiasingEnabled; + + bool myIs3dView; + + Handle(V3d_View) myV3dView; + Handle(AIS_InteractiveContext) myContext; + AIS_MouseGestureMap myDefaultGestures; + Graphic3d_Vec2i myClickPos; + + void updateView(); + + //! Setup mouse gestures. + void defineMouseGestures(); + + //! Set current action. + void setCurrentAction (CurrentAction3d theAction) + { + myCurrentMode = theAction; + defineMouseGestures(); + } + + //! Handle selection changed event. + void OnSelectionChanged(const Handle(AIS_InteractiveContext)& theCtx, + const Handle(V3d_View)& theView) Standard_OVERRIDE; + CurrentAction3d myCurrentMode; + Standard_Real myCurZoom; + QMap<ViewAction, QAction*> myViewActions; + QMap<RaytraceAction, QAction*> myRaytraceActions; + QMenu* myBackMenu; + QToolBar* myViewBar; +}; + +#endif diff --git a/samples/qt/Tutorial/.gitignore b/samples/qt/Tutorial/.gitignore new file mode 100644 index 0000000000..7ac6e6bc69 --- /dev/null +++ b/samples/qt/Tutorial/.gitignore @@ -0,0 +1,7 @@ +/debug +/release +*.sln +*.vcxproj* +.qmake.stash +/custom.bat +/custom.sh diff --git a/samples/qt/Tutorial/custom.bat b/samples/qt/Tutorial/custom.bat deleted file mode 100644 index b5eea5240f..0000000000 --- a/samples/qt/Tutorial/custom.bat +++ /dev/null @@ -1,4 +0,0 @@ -@echo off -rem Define QTDIR variable - -set "QTDIR=" diff --git a/samples/qt/Tutorial/custom.bat.template b/samples/qt/Tutorial/custom.bat.template new file mode 100644 index 0000000000..dda84faa21 --- /dev/null +++ b/samples/qt/Tutorial/custom.bat.template @@ -0,0 +1,5 @@ +@echo off +rem Rename this file to custom.bat, +rem and define QTDIR variable. + +set "QTDIR=" diff --git a/samples/qt/Tutorial/custom.sh b/samples/qt/Tutorial/custom.sh deleted file mode 100755 index d9705989ff..0000000000 --- a/samples/qt/Tutorial/custom.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -#Define QTDIR variable - -export QTDIR="" diff --git a/samples/qt/Tutorial/custom.sh.template b/samples/qt/Tutorial/custom.sh.template new file mode 100644 index 0000000000..52571f097b --- /dev/null +++ b/samples/qt/Tutorial/custom.sh.template @@ -0,0 +1,5 @@ +#!/bin/bash +# Rename this file to custom.sh, +# and define QTDIR variable. + +export QTDIR="" diff --git a/samples/qt/Tutorial/env.bat b/samples/qt/Tutorial/env.bat index 56b7eeb0c8..f44cfeb397 100755 --- a/samples/qt/Tutorial/env.bat +++ b/samples/qt/Tutorial/env.bat @@ -1,8 +1,10 @@ @echo off -call "%~dp0..\..\..\env.bat" %1 %2 %3 +if exist "%~dp0custom.bat" ( + call "%~dp0custom.bat" %1 %2 %3 +) -call "custom.bat" %1 %2 %3 +call "%~dp0..\..\..\env.bat" %1 %2 %3 set "RES_DIR=%~dp0win%ARCH%\%VCVER%\res" set "CSF_ResourcesDefaults=%RES_DIR%"